将数组字符串转换为intger c ++(初学者)

时间:2015-12-09 23:00:16

标签: c++ arrays iostream ifstream

我有一个文本文件,里面只包含数字,我已成功从文件中提取数字,将其存储在数组中

我的问题是数组是" 字符串"我不能对数组进行数学运算,如加法减法 我曾尝试使用atoi(array[i][j].c_str())将其转换为intger 但它只给我一个数字的第一个数字!

我的程序现在看起来像这样,我知道它是一团糟:(

#include <iostream>
#include <fstream> 
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
ifstream iFile("input.txt");      
string line;
string array[7][7];
for (int i=0;i<7;i++){
       for (int j=0;j<6;j++){
       getline(iFile,line);
        if (!line.empty()){
            array[i][j]=line;
       }
       else  {
            break;
       }
   }
}
cout<<"number of processes is:  "<<array[0][0]<<endl;
cout<<"resource types:  "<<array[1][0]<<endl<<endl;
cout<<"Allocation Matrix:"<<endl;
cout<<"   A B C D"<<endl;
cout<<"0: "<<array[2][0]<<endl;
cout<<"1: "<<array[2][1]<<endl;
cout<<"2: "<<array[2][2]<<endl;
cout<<"3: "<<array[2][3]<<endl;
cout<<"4: "<<array[2][4]<<endl;
cout<<"Max Matrix:"<<endl;
cout<<"   A B C D"<<endl;
cout<<"0: "<<array[3][0]<<endl;
cout<<"1: "<<array[3][1]<<endl;
cout<<"2: "<<array[3][2]<<endl;
cout<<"3: "<<array[3][3]<<endl;
cout<<"4: "<<array[3][4]<<endl;
cout<<"Need Matrix:"<<endl;
cout<<"   A B C D"<<endl;
//cout<<"0: "<<array[3][1]+array[2][1]<<endl;
//int c= atoi(array[3][1].c_str());
//int c2= atoi(array[3][1].c_str());
//cout<<c+c2<<endl;



  return 0;
}

我的input.txt文件如下所示:

5

4

0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4

0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6

1 5 2 0

1:0 4 2 0

编辑:

  

注意:如果有空行&gt;&gt;停止!

该程序基于银行家算法,该算法将input.txt中的第一个数字作为进程数

然后将第二个数字作为资源类型的数量 然后将下一个数字表示它们之间没有空行作为分配矩阵

然后

将下一个数字表示它们之间没有空行 max Matrix

这是我的问题,当我想在分配矩阵和最大矩阵之间进行减法时,因为两者都是字符串

对于1:0 4 2 0,它意味着对进程号1进行一些操作

1 个答案:

答案 0 :(得分:2)

您可以使用atoi,但在c++中您有更好的选择。

<{1>} c++您可以轻松使用stringstream转换这些类型。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int convert_str_to_int(const string& str) {
    int val;
    stringstream ss;
    ss << str;
    ss >> val;
    return val;
}

int main () {
    string str = "1024";
    int val = convert_str_to_int(str);
    cout << "Val is: " << val << ", val/2 is " << val/2 << endl;
}