我有这个程序,我想用整数形式从命令行传递的值填充表数组。但是字符串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);
}
}
}
答案 0 :(得分:0)
问题是你以错误的方式使用stringstream
。
通过撰写str >> s
,您将在流中获得eof
。
要解决此问题,您可以避免使用stringstream
,而是直接将value
分配给s
。
如果您想使用stringstream
,可以在写入s
之后将其重置为初始状态,如下所示:
str.str(std::string{});
str.clear();
再次使用
答案 1 :(得分:0)
isdigit函数测试如果char是数字,那么命令行
isdigit(*argv[i])
返回true是char *的第一个字符是一个数字。你想要的是将char *转换为整数,我建议你看一下atoi function。
但是,不需要用于打印结果的字符串转换。