我有这个程序,我想用从命令行传递的整数形式的值填充tables数组。但是,It字符串%s仅分配了参数6 ..问题出在哪里?
#include <iostream>
#include <cctype>
#include <locale>
#include <cstdlib>
#include <sstream>
#include <string>
using namespace std;
int main(int argc,char *argv[]){
int i;
int tables[100];
stringstream str;
string s;
int result;
char value;
if(argc <=1){
cout<<"NO ARGUMENTS PASSED"<<endl;
exit(0);
}
/*char value = *argv[1];
cout<<value<<endl;
str << value;
str >> s;
result = stoi(s,nullptr,10);
cout<<result<<endl;*/
for (i=1;i<argc;i++){
if(isdigit(*argv[i])){
value = *argv[i];
str<<value;
str>>s;
cout<<s<<endl;
tables[i-1] = stoi(s,nullptr,10);
}
}
}发布于 2016-10-07 21:19:09
问题是您使用stringstream的方式是错误的。
通过编写str >> s,您可以到达流中的eof。要解决这个问题,您可以避免使用stringstream,而是直接将value赋值给s。如果您想使用stringstream,您可以在写入s后将其重置回初始状态,如下所示:
str.str(std::string{});
str.clear();并再次使用它
发布于 2016-10-07 21:24:29
isdigit函数测试如果字符是数字,则命令行
isdigit(*argv[i])返回true是字符的第一个字符*是一个数字。你想要的是把一个字符*转换成一个整数,我建议看看atoi function。
但是,打印结果的字符串转换并不是必需的。
https://stackoverflow.com/questions/39917932
复制相似问题