您有两种选择:
我刚刚开始在C ++中的<fstream>
库上刷新自己,我正尝试将文本文件的第一行存储到3个整数变量中,所有变量都用空格分割。文本文件的第二行有一个字符串,我正在尝试获取我的字符串变量来存储它。但是,我不确定如何转到文件的下一行。该文件如下所示:
5 10 15
My name is Luke
我知道使用getline
来获取整行,然后转到下一行,但是我没有将第一行存储到一个变量中,而是将3存储到一个变量中,因此我不能使用getline()
一。这是我的代码。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream inFile;
ofstream outFile;
string name;
int x,y,z;
outFile.open("C:\\Users\\luked\\Desktop\\Test.txt");
outFile << 5 << " " << 10 << " " << 15 << endl << "My name is Luke";
outFile.close();
inFile.open("C:\\Users\\luked\\Desktop\\Test.txt");
inFile >> x >> y >> z;
getline(inFile, name);
cout << x << " " << y << " " << z << " " << endl << name;
return 0;
}
替换
inFile >> x >> y >> z;
getline(inFile, name);
由
inFile >> x >> y >> z;
inFile.ignore();
getline(inFile, name);
因为
[std::getline
读取直到遇到定界符或文件结尾,这是在]之后的换行符>
5 10 15\n ^ // you need to ignore this
您可以通过]忽略它>
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); getline(inFile, name);
您有两种选择:
您可以使用operator>>
读取3个整数,然后使用ignore()
ifstream
读取,直到跳过新行,然后可以使用std::getline()
读取第二行:
#include <iostream> #include <string> #include <fstream> #include <limits> using namespace std; int main(int argc, char **argv) { ifstream inFile; ofstream outFile; string name; int x,y,z; outFile.open("C:\\Users\\luked\\Desktop\\Test.txt"); outFile << 5 << " " << 10 << " " << 15 << "\n" << "My name is Luke"; outFile.close(); inFile.open("C:\\Users\\luked\\Desktop\\Test.txt"); inFile >> x >> y >> z; infile.ignore(numeric_limits<streamsize>::max(), '\n'); getline(inFile, name); cout << x << " " << y << " " << z << " " << endl << name; return 0; }
否则,尽管您有什么想法,您实际上可以使用
std::getline()
来读取第一行。之后,只需使用std::istringstream
从该行读取整数。然后,您可以使用std::getline()
读取第二行:#include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; int main(int argc, char **argv) { ifstream inFile; ofstream outFile; string line, name; int x,y,z; outFile.open("C:\\Users\\luked\\Desktop\\Test.txt"); outFile << 5 << " " << 10 << " " << 15 << "\n" << "My name is Luke"; outFile.close(); inFile.open("C:\\Users\\luked\\Desktop\\Test.txt"); getline(inFile, line); istringstream(line) >> x >> y >> z; getline(inFile, name); cout << x << " " << y << " " << z << " " << endl << name; return 0; }
您有两种选择: