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

标签 c++

用户输入 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/

相关文章:

c++ - c++/cx 中的 storagefile::ReadAsync 异常?

c++ - Visual Studio 2005 中的 Lambda 函数替代品——Boost 库

c++ - 使用 DWORD_PTR

c++ - 双向链表 C++ 中的 add 方法问题

c++ - 引入着色器并不再绘制

c++ - 命名空间会破坏 ABI 吗?

c++ - 一个有大小限制的类STL容器应该如何实现?

c++ - 破解另一个库的内存

c++ - 确保我们初始化每个变量一次且仅一次

c++ - C++ 中数据聚合和后处理的习惯用法