如何将字符串中的多个数字转换为整数

时间:2018-05-03 00:17:49

标签: c++ string type-conversion int

我很困惑如何获取包含数字的多个字符串并将它们转换为int。我有多行字符串存储在数据中的int中,然后将它们插入一个名为values的二维数组中。之前在StackOverflow上发布了一个类似的问题;但它似乎对我不起作用。我打印出数据中的每一行,数据中的每个字符串如下。

 75
 95 64
 17 42 82
 18 35 87 10

然而,当我通过在main中使用两个for循环从值输出数字时,它输出为this。

75 0 0 0 95 64 0 0

95 64 0 0 17 42 82 0

17 42 82 0 18 35 87 10

18 35 87 10 0 0 0 0

我在打印sizeof(values)和sizeof(values [0])时发现数组中有8列和8个元素;然而,似乎程序终止作为最后一个打印语句,我打印hello不会发生。我在下面提供了我使用的代码。我想知道为什么会这样 以及如何解决它?感谢。

//const char DELIMITER = ' ';

int **values, // This is your 2D array of values, read from the file.
    **sums;   // This is your 2D array of partial sums, used in DP.

int num_rows; // num_rows tells you how many rows the 2D array has.
          // The first row has 1 column, the second row has 2 columns, and
          // so on...

bool load_values_from_file(const string &filename) {
ifstream input_file(filename.c_str());
if (!input_file) {
    cerr << "Error: Cannot open file '" << filename << "'." << endl;
    return false;
}
input_file.exceptions(ifstream::badbit);
string line;
vector<string> data;
try {
    while (getline(input_file, line)) {
        data.push_back(line);
        num_rows ++;
    }
    input_file.close();
} catch (const ifstream::failure &f) {
    cerr << "Error: An I/O error occurred reading '" << filename << "'.";
    return false;
}
for(int x = 0; x < data.size(); x++){
    cout << data[x] << endl;
}

//https://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-into-integers
//Help on making multiple numbers in a string into seperate ints
values = new int*[num_rows];
vector<int> v;
for(int y = 0; y < data.size(); y++){
    istringstream stream(data[y]);
    values[y] = new int[y + 1];
    int z = 0;

    while(1) {
       int n;
       stream >> n;
       if(!stream)
          break;
       values[y][z] = n;
       z++;
    }
    z = 0;
}
sums = values;

return true;
}

int main(int argc, char * const argv[]) {

if (argc != 2) {
    cerr << "Usage: " << argv[0] << " <filename>" << endl;
    return 1;
}
string filename(argv[1]);
if (!load_values_from_file(filename)) {
    return 1;
}

cout << sizeof(values) << endl;
cout << sizeof(values[0]) << endl;

for(int x = 0; x < sizeof(values); x++){
    for(int y = 0; y < sizeof(values[x]); y++){
        cout << values[x][y] << endl;
    }
    cout << endl;
}
cout << "hello" << endl;


return 0;

}

1 个答案:

答案 0 :(得分:1)

见:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;
int main()
{
    string str;
    ifstream fs("D:\\Myfolder\\try.txt", ios::in);
    stringstream ss;
    std::string item;
    if (fs.is_open())
    {       
        ss << fs.rdbuf();
        str = ss.str();
        cout << str << endl;
        fs.close();
    }

    cout << "\n\n Output \n\n";
    while (std::getline(ss, item, ' '))
    {
        cout << std::atoi(item.c_str()) <<" ";
    }

    return 0;
}