将字符串存储到文件下一行的变量中
Store string into a variable in next line of a file
我刚刚开始在C++的<fstream>
库刷新自己,我正在尝试将文本文件的第一行存储到 3 个整数变量中,所有变量都用空格分割。文本文件的第二行有一个字符串,我正在尝试让我的字符串变量来存储它。但是,我不确定如何转到文件的下一行。该文件如下所示:
5 10 15
My name is Luke
我知道使用getline
获取整行然后转到下一行,但我没有将第一行存储到一个变量中,而是将 3 行存储到 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);
因为
为什么在"cin"之后使用">getline"时需要cin.ignore((,而多次使用"cin"时不需要?
并深入解释
为什么 std::getline(( 在格式化提取后跳过输入?
std::getline
读取,直到遇到文件的分隔符或结尾,这里是紧随其后的换行符
5 10 15n
^
// 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;
}
否则,尽管您声称"我不能将 getline(( 用于 [第一行]",但您实际上可以使用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;
}
相关文章:
- 在C++的一行中初始化多个变量
- 将字符串存储到文件下一行的变量中
- 一行输入到多个变量
- 使用更改此变量的函数在同一行中打印引用变量
- 如何从文本文件中读取一行并将其分为不同的变量
- 如何在一行中从不同的变量(数据类型)创建一个字符数组?
- 如何在同一行中使用具有多个变量的 getline()
- 创建一个字符串变量,并在同一行上要求输入
- 引用变量在下一行程序执行后显示未找到的行为
- c++从ifstream中读取一行的最后一个变量
- 如何将一行数字读入不同的变量
- 从.txt文件中读取一行,然后插入变量
- 无法删除 txt 文件中 getline(cin , (变量)) 之后的下一行
- 将一行文件读入对象中的两个变量
- 我如何在同一行输入2个不同的变量,同时使用setw进行格式化
- 如何解析一行上变量数量未知的文本文件?
- 在一行中初始化多个私有变量
- c++读取文件,将每一行放入数组,对每个变量做一些操作
- 在C++中,你能在同一行声明多个引用变量吗
- 在c++中对齐(格式化)输出//多个变量在一行中