首页 > 解决方案 > 如何检查一行中的第二个字符串是否为数字?

问题描述

我使用 c++ 作为我的编程语言。我正在尝试检查 line 的第二个字符串值是否是使用isstringstream将其转换为int.

检查字符串的第一个值很容易,因为它是第一个值,但是如何检查字符串的第二个值是否为 int。我几乎没有学过getline(),所以我宁愿方法不太复杂。

我一直在使用 if 语句,但似乎没有任何效果。

44 68 usable BothMatch  
100 90 usable BothMatch
110 120 usable BothMatch
183 133 usable BothMatch
170 140 usable BothMatch
188 155 usable BothMatch

标签: c++visual-c++

解决方案


一种可能性是使用 astd::istringstream在每一行上获取单个单词。遍历每个单词时,增加一个计数器,以跟踪已处理的单词数。

如果需要处理每一行的第二个字,则必须检查计数器值是否等于 1(假设移动到新行时,计数器初始化为 0)。

由于您提到可以检查给定字符串是否为数字,因此我没有提供该isNumber()函数的实现。

下面有一些源代码打印每一行+每个单词,“模拟”对你的isNumber()函数的调用,每个第二个单词(在输入的每一行上)。

#include <iostream>
#include <sstream>
#include <string>

bool isNumber(const std::string& s) {
    // TODO
    return true;
}

int main() {
    std::string s;
    std::string word;

    int lineNum = 0;
    int wordNum = 0;

    while (std::getline(std::cin, s)) {
        std::cout << "Line number " << lineNum << ": " << s << "\n";
        std::istringstream iss(s);
        wordNum = 0;

        while (iss >> word) {
            std::cout << "\tWord number " << wordNum << " in line "
                  << lineNum << ": " << word << "\n";

            if (wordNum == 1 && isNumber(word))
                std::cout << "'" << word << "' is a number\n";

            wordNum++;
        }

        lineNum++;
    }

    return 0;
}

推荐阅读