gpt4 book ai didi

c++ - 从文件中获取输入问题 C++

转载 作者:行者123 更新时间:2023-11-30 02:54:50 24 4
gpt4 key购买 nike

我一直在尝试从 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 的信息,但似乎找不到任何解决方案,因此我们将不胜感激。

谢谢

最佳答案

读取整数后,换行符保留在输入流中:

// Always check result to ensure variables correctly assigned a value.
if (input_stream >> value)
{
}

然后,对 getline() 的调用读取换行符并停止,生成一个空字符串。要更正,请在调用 getline() 之前使用换行符(选项包括使用 getline()ignore())。

注意有一个版本 std::getline()它接受 std::string 作为其参数,以避免使用固定大小的 char 数组,这在发布的代码中使用不正确。

关于c++ - 从文件中获取输入问题 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com