Reading through file using ifstream(使用 ifstream 读取文件)
问题描述
我正在尝试从文件中读取:该文件是多行的,基本上我需要检查每个单词".词是任何非空间.
I am trying to read from file: The file is multiline and basically i need to go over each "word". Word being anything non space.
示例输入文件将是:
Sample input file would be:
示例文件:
测试二维
字 3.5
输入
{
测试 13.5 12.3
另一个{
测试 145.4
}
}
test 2d
word 3.5
input
{
test 13.5 12.3
another {
testing 145.4
}
}
所以我尝试了这样的事情:
So I tried something like this:
ifstream inFile(fajl.c_str(), ifstream::in);
if(!inFile)
{
cout << "Cannot open " << fajl << endl;
exit(0);
}
string curr_str;
char curr_ch;
int curr_int;
float curr_float;
cout << "HERE
";
inFile >> curr_str;
cout << "Read " << curr_str << endl;
问题是当它读取新行时它只是挂起.我在测试 13.5 之前阅读了所有内容但是一旦它到达那条线,它就什么也不做.谁能告诉我我做错了什么?关于如何做到这一点的任何更好的建议???
The problem is when it reads new line it just hangs. I read everything before test 13.5 but once it reaches that line it doesnt do anything. Anyone can tell me what I am doing wrong? Any better suggestion on how to do this???
当时我基本上需要浏览文件并输入一个单词"(非白色字符).我
I essentially need to go through file and go one "word" (non white char) at the time. I
谢谢
推荐答案
您打开了一个文件 'inFile' 但正在从 'std::cin' 中读取任何特殊原因?
You open a file 'inFile' but are reading from the 'std::cin' any particular reason?
/*
* Open the file.
*/
std::ifstream inFile(fajl.c_str()); // use input file stream don't.
// Then you don't need explicitly specify
// that input flag in second parameter
if (!inFile) // Test for error.
{
std::cerr << "Error opening file:
";
exit(1);
}
std::string word;
while(inFile >> word) // while reading a word succeeds. Note >> operator with string
{ // Will read 1 space separated word.
std::cout << "Word(" << word << ")
";
}
这篇关于使用 ifstream 读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ifstream 读取文件
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
