使用 ifstream 读取文件

2023-10-18C/C++开发问题
21

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6