gpt4 book ai didi

c++ - 如何从文件中读取整行(带空格)?

转载 作者:太空狗 更新时间:2023-10-29 19:44:05 26 4
gpt4 key购买 nike

我正在使用 STL。我需要从文本文件中读取行。如何读取直到第一个 \n 而不是第一个 ' ' (空格)的行?

例如,我的文本文件包含:

Hello world
Hey there

如果我这样写:

ifstream file("FileWithGreetings.txt");
string str("");
file >> str;

然后 str 将只包含“Hello”,但我需要“Hello world”(直到第一个 \n)。

我想我可以使用 getline() 方法,但它需要指定要读取的符号数。就我而言,我不知道应该阅读多少个符号。

最佳答案

你可以使用getline:

#include <string>
#include <iostream>

int main() {
std::string line;
if (getline(std::cin,line)) {
// line is the whole line
}
}

关于c++ - 如何从文件中读取整行(带空格)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15362367/

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