将令牌存储到数组中
作为 C++ 的新手,我正在尝试创建一个统计程序来练习编码。我希望获得一个文本文件,读取它并将值存储到可以执行数学运算的数组中。我被困
main ()
{
char output[100];
char *charptr;
int age[100];
ifstream inFile;
inFile.open("data.txt");
if(!inFile)
{
cout<<"didn't work";
cin.get();
exit (1);
}
inFile.getline(output,100);
charptr = strtok(output," ");
for (int x=0;x<105;x++)
{
age[x] = atoi(charptr);
cout<<*age<<endl;
}
cin.get();
}
在上面的代码中,我试图将主题年龄存储到 int 数组“age”中,将年龄保留在文件的第一行。我打算如上所述使用 strtok,但我无法将标记转换为数组。
正如你所看到的,我是一个十足的菜鸟,请耐心等待,因为我正在自学。 :)
谢谢
PS:我已经阅读了类似的线程,但无法遵循那里给出的详细代码。
A novice at C++, i am trying to create a stats program to practice coding. i am hoping to get a text file, read it and store values into arrays on which i can perform mathematical operations. i am stuck here
main ()
{
char output[100];
char *charptr;
int age[100];
ifstream inFile;
inFile.open("data.txt");
if(!inFile)
{
cout<<"didn't work";
cin.get();
exit (1);
}
inFile.getline(output,100);
charptr = strtok(output," ");
for (int x=0;x<105;x++)
{
age[x] = atoi(charptr);
cout<<*age<<endl;
}
cin.get();
}
in the code above, I am trying to store subject ages into the int array 'age', keeping ages in the first line of the file. I intend to use strtok as mentioned, but i am unable to convert the tokens into the array.
As you can obviously see, I am a complete noob please bear with me as I am learning this on my own. :)
Thanks
P.S: I have read similar threads but am unable to follow the detailed code given there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for
循环存在一些问题:age
有 100 个元素,但for
中存在终止条件,因此可能会越界> 循环是x < 105
charptr
是否为 NULLfor
循环内不后续调用strtok()
age
元素不正确以下是
for
循环的修复示例:由于这是 C++,建议:
std::vector
而不是固定大小的数组std::getline()
以避免指定固定大小的缓冲区来读取行,std::copy()
和istream_iterator
来解析整数行例如:
There are a few issues with the
for
loop:age
having 100 elements, but terminating condition infor
loop isx < 105
charptr
being NULL prior to usestrtok()
insidefor
loopage
elements is incorrectThe following would be example fix of the
for
loop:As this is C++, suggest:
std::vector<int>
instead of a fixed size arraystd::getline()
to avoid specifying a fixed size buffer for reading a linestd::copy()
withistream_iterator
for parsing the line of integersFor example: