【发布时间】:2013-05-24 21:31:53
【问题描述】:
我一直在尝试从 C++ 中的 .txt 文件中读取一些信息,但它并没有像我预期的那样工作。下面是一些示例代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[255];
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
而 test.txt 包含:
1234
WordOne WordTwo
我期望代码打印文本文件中包含的两行,但我只是得到:
1234
我一直在阅读有关 getline 和 istream 的信息,但似乎找不到任何解决方案,因此不胜感激。
谢谢
【问题讨论】:
-
尝试打印另一个 getline 的输出,看看你发现了什么。这与是否使用换行符有关。
-
我猜这是因为 getline 在第一个字符串 (1234) 之后找到换行符并停止。
标签: c++ file input getline istream