我如何...如何将txt文件的每一行存储到一个单独的变量中,然后将它们打印到控制台屏幕?
问题描述:
如何将txt文件的每一行存储到一个单独的变量中,然后将它们打印到控制台屏幕?
我尝试过:
How do I store each line of a txt file into a separate variable then print them to the console screen?
What I have tried:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream inputFile("C:/Users/jacob/OneDrive/Desktop/cpp/File List to Txt/Files.txt");
string line;
while (getline(inputFile,line))
{
istringstream ss(line);
string name;
string var1, var2, var3;
ss >> name >> var1 >> var2 >> var3;
cout <<name << endl << endl;
}
}
答
读取每一行并打印它可以这样完成:
Reading each line and printing it can be done like so:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream inputFile("C:/Users/jacob/OneDrive/Desktop/cpp/File List to Txt/Files.txt");
string line;
while (getline(inputFile,line))
{
cout << line << endl;
}
}
将它存储在单独的变量中到底是什么意思?基于该描述,我建议将所有行读入数组。您的代码建议您尝试将单词拆分为单词?
What exactly do you mean with storing it in a separate variable? Based on that description I would suggest reading all the lines into an array. Your code suggests you're trying to split up the line in words though?