在我的程序中,带有要读取的值(最多 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
如何将读取的 char 值转换为 int?
你可以通过写来解决这个问题
array[i] = x - '0';
ASCII 字符如'1'
or '5'
不能直接转换以获得它们的数字等价物。确保您在执行此操作时一直在读取数字字符,例如使用std::isdigit() http://en.cppreference.com/w/cpp/string/byte/isdigit功能。
至于问题编辑后您最关心的问题:
或者还有其他方法可以将它们读取为 int 类型吗?
常用的读入方法int
类型只是应用std::istream& operator>>(std::istream&, int&)
like so
int array[10];
int i = 0;
int x_int;
while ( the_file >> x_int && i < 10) {
array[i] = x_int;
++i;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)