使用 ifstream 读取文件 [英] Reading through file using ifstream

查看:46
本文介绍了使用 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 读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆