【问题标题】:When converting a string array of numbers to an array of integers the elements are turned to 0s将数字字符串数组转换为整数数组时,元素将变为 0
【发布时间】:2017-12-22 08:28:25
【问题描述】:

当我将信息转换为整数并打印出数组时,输出仅为 0。 info 中的每个元素都是作为字符串输入的数字,该字符串取自文本文件。例如:513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79。我使用 strtok 删除了行中的空格并将数字输入到 info 中。当我打印出信息时,所有的数字都在那里。如何让这些正确转换?

string info[1000]
int student[18];
for (int i=1; i<18; i++){
    //cout << info[i] << endl;
    stringstream convert(info[i]);
    convert << student[n];
    cout << student[n] << endl;
    n++;
}

【问题讨论】:

  • str 是什么类型? n 是什么(和 i 有什么关系)?
  • 这段代码无法编译
  • 注意“>”的区别。 (如果您没有编写不必要的通用代码,编译器会帮助您。)
  • 我建议你使用istringstream,就像cin一样使用。

标签: c++ arrays file io stringstream


【解决方案1】:

字符串流是我最喜欢的工具。它们会自动转换数据类型(大部分时间),就像 cin 和 cout 一样。这是一个带有字符串流的示例。它们包含在库中

string info = "513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79";
int student[18];

stringstream ss(info);

for (int i=0; i< 18; i++){
   ss >> student[i];
   cout << student[i] << endl;;
} 

这是一个repl https://repl.it/J5nQ

【讨论】:

    猜你喜欢
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多