用户输入int
和string
,然后程序将它们存储到C ++中的两个单独的列表中。
我在if (isNum(input))
上遇到错误-参数无效;无法将输入从char转换为字符串。
#include <list>
#include <iostream>
using namespace std;
bool isNum(string s)
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int main(int argv, char* argc[])
{
int i;
string str;
list<int> l;
list<string> s;
char input;
do {
cin >> input;
if (isNum(input))
{
i = input;
l.push_front(i);
}
else
{
str = input;
s.push_back(str);
}
l.push_back(i);
s.push_back(str);
} while (i != 0);
l.sort();
list<int>::const_iterator iter;
for (iter = l.begin(); iter != l.end(); iter++)
cout << (*iter) << endl;
}
答案 0 :(得分:0)
那不是那么容易...但是我让流来决定是int
还是string
:
#include <list>
#include <string>
#include <iostream>
int main() // no parameters required for our program
{
std::list<std::string> strings;
std::list<int> numbers;
int num;
do {
std::string str;
if (std::cin >> num) { // try to read an integer if that fails, num will be 0
numbers.push_front(num);
}
else if (std::cin.clear(), std::cin >> str) { // reset the streams flags because
strings.push_front(str); // we only get here if trying to
num = 42; // no, don't exit // extract an integer failed.
}
} while (std::cin && num != 0); // as long as the stream is good and num not 0
strings.sort();
std::cout << "\nStrings:\n";
for (auto const &s : strings)
std::cout << s << '\n';
std::cout.put('\n');
numbers.sort();
std::cout << "Numbers:\n";
for (auto const &n : numbers)
std::cout << n << '\n';
std::cout.put('\n');
}
foo
5
bar
3
aleph
2
aga
1
0
Strings:
aga
aleph
bar
foo
Numbers:
0
1
2
3
5
关于您的代码的几件事:
using namespace std;
,因为它会将整个名称空间std溢出到全局名称空间中。for
循环。易于编写,易于阅读。