我需要编码从File读取并存储在不同的数组中!!!
例如:
保罗23 54john 32 56
我的要求如下:我需要将paul,john
存储在字符串数组中,将23,32
存储在一个整数数组中;类似54,56
在另一个int
数组中。
我从文件中读取输入并打印出来,但我无法保存在3个不同的数组中。
int main()
{
string name;
int score;
ifstream inFile ;
inFile.open("try.txt");
while(getline(inFile,name))
{
cout<<name<<endl;
}
inFile.close();
}
亲切地建议我做一些逻辑,我真的很感激...... !!!
答案 0 :(得分:0)
我认为你是编程新手?还是C ++的新手?所以我提供了示例代码以帮助您入门。 :)
#include <string>;
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> name;
vector<int> veca, vecb;
string n;
int a, b;
ifstream fin("try.txt");
while (fin >> n >> a >> b) {
name.push_back(n);
veca.push_back(a);
vecb.push_back(b);
cout << n << ' ' << a << ' ' << b << endl;
}
fin.close()
return 0;
}
答案 1 :(得分:0)
您可以尝试以下代码:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
int main()
{
std::string fileToRead = "file.log";
std::vector<int> column2, column3;
std::vector<std::string> names;
int number1, number2;
std::string strName;
std::fstream fileStream(fileToRead, std::ios::in);
while (fileStream>> strName >> number1 >> number2)
{
names.push_back(strName);
column2.push_back(number1);
column3.push_back(number2);
std::cout << "Value1=" << strName
<< "; Value2=" << number1
<< "; value2=" << number2
<< std::endl;
}
fileStream.close();
return 0;
}
这个想法是将文件中的第一列读取为字符串(strName),然后将其推送到向量(名称)。类似地,第一列和第三列首先被读入number1和number2,然后分别被推入名为column1和column2的向量中。
运行它会得到以下结果:
Value1=paul; Value2=23; value2=54
Value1=john; Value2=32; value2=56