gpt4 book ai didi

c++ - 输入 int 和 str 并将它们存储到两个单独的列表中

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:50 24 4
gpt4 key购买 nike

用户输入 intstring,程序将它们存储到 C++ 中的两个单独的列表中。

我在 if (isNum(input)) 上收到错误 - 参数无效;无法将输入从字符转换为字符串。

#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;
}

最佳答案

这不是那么容易...但是我会让流来决定它是 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 循环。更易于编写,更易于阅读。

关于c++ - 输入 int 和 str 并将它们存储到两个单独的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com