c++ - 将读取的 char 转换为 int c++

标签 c++ terminal

在我的程序中,带有要读取的值(最多 2 位数字)的文件名在终端中给出,我的 main() 如下所示:

int main ( int argc, char *argv[] )
{
   //assume argv[1] is a filename to open
   ifstream the_file ( argv[1] )
   if ( !the_file.is_open() ){
      cout<<"Could not open file" << endl;
      return 0;
   }

   char x;
   int array[10];
   int x_int;
   while ( the_file.get ( x ) ){
        for (int i=0; i<10;i++){
             array[i] = (int)x;
        }
   }
      
}

但是,我得到了一些奇数。

我的错误肯定是在 array[i] = (int)x; 行,但是

如何将读取的 char 值转换为 int?或者有没有其他方法可以将它们读取为 int 类型?

我想让从输入文件中获取的值作为整数,而不是单个数字

我的实际输入文件 (.txt) 是:

75
95
1
2
45
65
98
6
7
9

最佳答案

how can I convert read char value to int?

你可以通过写来解决这个问题

array[i] = x - '0';

'1''5' 等 ASCII 字符不能直接转换为数字等价物。确保您在这样做时一直在阅读数字字符,例如使用 std::isdigit()功能。


至于问题编辑后您最关心的问题:

Or is there any other method to read them as int type?

读取 int 类型的常用方法就是像这样应用 std::istream& operator>>(std::istream&, int&)

int array[10];
int i = 0;
int x_int;
while ( the_file >> x_int && i < 10) {
    array[i] = x_int;
    ++i;
}

关于c++ - 将读取的 char 转换为 int c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33900768/

相关文章:

terminal - 进程接收 SIGTTYIN/TTOU 而不是阻塞的历史原因是什么?

java - 如何从java程序在终端运行命令?

ubuntu - GPG : ify: skipped: public key not found when I made the encryption myself

javascript - 从外部目录启动 grunt

ruby - gem install faSTLane -> 没有这样的名称

c# - Visual Studio C# 项目中未显示 C++ 错误

c++ - 围绕另一个点旋转一个点 (2D)

c++ - 为什么在 SETcc 之前进行 XOR?

java - 以下情况的替代方案

c++ - 内省(introspection) C++ 中的结构定义?