【发布时间】:2017-05-04 17:41:18
【问题描述】:
假设我有一个文本文件:
83 71 69 97Joines, William B.
100 85 88 85Henry, Jackson Q.
我想将每个数字存储在一个整数数组中,并将每个全名存储到一个字符串数组中(例如,全名是Joines, William B)。
最好的方法是什么,因为我争论过使用while (inputFile >> line) 还是while (getline(inputFile, line)) 会更好。我不知道是一次读一个单词还是一次读一行更容易。我的主要问题是将97Joines, William B. 拆分为97 和Joines, William B.,我不明白如何在C++ 中进行操作。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
int counter = 0;
int scores[40];
string names[10];
string filename, line;
ifstream inputFile;
cout << "Please enter the location of the file:\n";
cin >> filename;
inputFile.open(filename);
while (inputFile >> line) {
// if line is numeric values only, do scores[counter] = line;
// if it is alphabet characters only, do names[counter] = line;
//if it is both, find a way to split it // <----- need help figuring out how to do this!
}
inputFile.close();
}
【问题讨论】:
-
最好的方法是在stackoverflow中搜索“c++ read file array int”并研究帖子。关于如何从文本文件中读取数据,已经有很多类似的问题。
-
更好的方法是使用结构或类对文本行进行建模,并使用这些结构的向量。不要使用并行数组,因为它们容易出现同步问题(尤其是在排序时)。
-
我的主要问题是关于
97Joines, William B.,我将如何拆分它,因为它们被作为一个整体读入。应该是97和Joines, William B.