C++ 将文本文件读入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10396906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ read text file into an array
提问by pjmil
I'm trying to read a text file containing 20 names into an array of strings, and then print each string to the screen.
我正在尝试将包含 20 个名称的文本文件读入一个字符串数组,然后将每个字符串打印到屏幕上。
string monsters[20];
ifstream inData;
inData.open("names.txt");
for (int i=0;i<monsters->size();i++){
inData >> monsters[i];
cout << monsters[i] << endl;
}inData.close();
However when I run this code the loop is executed but nothing is read into the array. Where have I gone wrong?
但是,当我运行此代码时,将执行循环但没有将任何内容读入数组。我哪里错了?
回答by penguinvasion
Your for loop terminating condition is wrong:
您的 for 循环终止条件是错误的:
i < monsters->size()
This will actually call size() on the first string in your array, since that is located at the first index. (monsters is equivalent to monsters[0]) Since it's empty by default, it returns 0, and the loop will never even run.
这实际上会在数组中的第一个字符串上调用 size(),因为它位于第一个索引处。(monsters 等价于monsters[0]) 由于默认为空,所以返回0,循环永远不会运行。
Remember, C++ does not have a size() operator for arrays. You should instead use the constant 20 for your terminating condition.
请记住,C++ 没有用于数组的 size() 运算符。您应该改为使用常量 20 作为终止条件。
i < 20
回答by Software_Designer
monsters->size()
is 0
at runtime. Change that line to for (int i=0;i<20;i++)
.
monsters->size()
是0
在运行时。将该行更改为for (int i=0;i<20;i++)
.
string monsters[20];
ifstream inData;
inData.open("names.txt");
for (int i=0;i<20;i++){
inData >> monsters[i];
cout << monsters[i] << endl;
}inData.close();