如何从 C++ 中的 fstream 中读取两个单词然后一行?
How to read two words and then a line from an fstream in C++?
我 运行 在用 C++ 编码时遇到了一点问题。我有一个输入(fstream
将要读取的文件):
1 2
three four five six
我想用这个输入做的是:取第一行,并将其分成两个 string
变量:一个有 1,一个有 2。之后,对于下一行,我想使用某种形式的 getline()
可能将 "three four five six" 作为一个 string
。我目前已经尝试过:我有一些代码声明了三个字符串变量:
#include<string>
// Main function...
string str1, str2, str3;
fstream inf;
inf.open('somefile.txt');
inf >> str1 >> str2 >> str3;
inf.close();
这段代码正确地接受了“1”和“2”,但它只接受了下一行的第一个字符。我在这里做错了什么?
如有任何帮助,我们将不胜感激。谢谢!
忽略\n
后使用std::getline()
使用ignore()
得到整行字符串如下
#include<string>
#include<fstream>
#include<iostream>
int main(){
std::string str1, str2, str3;
std::fstream inf;
inf.open("somefile.txt");
inf >> str1 >> str2;
inf.ignore();
std::getline(inf, str3);
inf.close();
//Displying them
std::cout<<str1<<" "<<str2<<" "<<str3;
}
我 运行 在用 C++ 编码时遇到了一点问题。我有一个输入(fstream
将要读取的文件):
1 2
three four five six
我想用这个输入做的是:取第一行,并将其分成两个 string
变量:一个有 1,一个有 2。之后,对于下一行,我想使用某种形式的 getline()
可能将 "three four five six" 作为一个 string
。我目前已经尝试过:我有一些代码声明了三个字符串变量:
#include<string>
// Main function...
string str1, str2, str3;
fstream inf;
inf.open('somefile.txt');
inf >> str1 >> str2 >> str3;
inf.close();
这段代码正确地接受了“1”和“2”,但它只接受了下一行的第一个字符。我在这里做错了什么?
如有任何帮助,我们将不胜感激。谢谢!
忽略\n
后使用std::getline()
使用ignore()
得到整行字符串如下
#include<string>
#include<fstream>
#include<iostream>
int main(){
std::string str1, str2, str3;
std::fstream inf;
inf.open("somefile.txt");
inf >> str1 >> str2;
inf.ignore();
std::getline(inf, str3);
inf.close();
//Displying them
std::cout<<str1<<" "<<str2<<" "<<str3;
}