Vla*_*mir 3 c++ io fstream stl file
我正在使用STL.我需要从文本文件中读取行.如何读取行直到第一行(\n而不是第一行' '(空格))?
例如,我的文本文件包含:
Hello world
Hey there
Run Code Online (Sandbox Code Playgroud)
如果我这样写:
ifstream file("FileWithGreetings.txt");
string str("");
file >> str;
Run Code Online (Sandbox Code Playgroud)
然后str将只包含"你好",但我需要"Hello world"(直到第一个\n).
我以为我可以使用该方法,getline()但它要求指定要读取的符号数.就我而言,我不知道应该阅读多少个符号.
你可以使用getline:
#include <string>
#include <iostream>
int main() {
std::string line;
if (getline(std::cin,line)) {
// line is the whole line
}
}
Run Code Online (Sandbox Code Playgroud)