【问题标题】:convert an array string to intger c++ (beginner)将数组字符串转换为整数 c++(初学者)
【发布时间】:2015-12-09 23:00:16
【问题描述】:

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

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

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

#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

编辑:

注意:如果有空行>>停止!

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

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

然后将它们之间没有空行的下一个数字作为最大矩阵

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

1:0 4 2 0表示对1号进程进行一些操作

【问题讨论】:

  • 1:0 是错字吗? : 应该是一个空格吗?如果不是,那是什么意思?
  • 您的 input.txt 文件中的每个数字之间似乎都有一个空格,这意味着所有数字实际上每个只有一个数字。这可以解释为什么 atoi() 只选择第一个数字。
  • 说实话,我不太明白这个问题。请edit您的帖子包含实际和期望的行为以及明确的问题陈述。
  • 为什么把数字读成字符串?试着读成数字。

标签: c++ arrays iostream ifstream


【解决方案1】:

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

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;
}

【讨论】:

  • 基本正确。需要检查ss &gt;&gt; val; 是否真的读到了一些东西。示例:val 的内容将在输入“fubar”时未定义。推荐stringstream ss(str);代替默认构造函数,然后插入字符串。
猜你喜欢
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
相关资源
最近更新 更多