我在ifstream
旁边使用getline
,以便从整数文本文件中读取所有输入。输入被构造为邻接矩阵。现在,我在读取每行第一个空格之后的剩余数字时遇到了麻烦。
**我已经处理了示例输入,并确认它仅在每行中打印第一个数字(row [0 ... n],col [0])。
示例输入:
0 1 0
1 0 1
0 1 0
示例输出:
0
1
0
这里是源代码:
// Prompt user for input
cout <<"\nEnter filename: ";
cin >> fileName;
cout << "Enter a start vertex: ";
cin >> startVertex;
// Assume max size is 25 vertices
pointer = new int[25];
// Fill pointer with contents
ifstream newFile(fileName);
int x = 0;
while(getline(newFile, fileName)){
pointer[x] = stoi(fileName); //cast string to int
x++;
}
newFile.close();
cout << "Count = " << count << endl; //Test counter
for (int i = 0; i < x; i++){
cout << pointer[i] << " " << endl; // Test pointer contents
}
[std::getline()
读取整行输入,例如,它读取"0 1 0"
(第一行)。
然后std::stoi
的(有点令人惊讶)行为起作用:
这意味着,丢弃所有空白字符(通过调用isspace()进行标识,直到找到第一个非空白字符,然后使用尽可能多的字符以形成有效的base-n(其中n = base)< [整数表示并将它们转换为整数值。有效的整数值包括以下部分:
stoi
仅解析第一个数字0
并返回它。因此,您仅解析每行的第一个数字。 您需要按元素而不是按行读取文件:
ifstream newFile(fileName);
int val;
int x = 0;
while(newFile >> val){
pointer[x] = val;
x++;
}
newFile.close();
作为无关的附加内容:考虑文件包含25个以上条目时会发生什么。考虑使用std::vector
而不是普通数组。