在我的程序中,带有要读取的值(最多 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/