-2

I'm using c++ as my programming language. I'm trying to check if the second string value of line is a number after using isstringstream to convert it into an int.

Checking the first value of the string is easy since it's the first value, but how do you check if the second value of the string is an int. I barely learned getline() so I would prefer method not too complicated.

I have been using if statements but nothing seems to be working.

44 68 usable BothMatch  
100 90 usable BothMatch
110 120 usable BothMatch
183 133 usable BothMatch
170 140 usable BothMatch
188 155 usable BothMatch
YSC
  • 38,212
  • 9
  • 96
  • 149
  • 1
    Post some code. –  Nov 12 '18 at 17:03
  • Possible duplicate of https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it also maybe https://stackoverflow.com/questions/46260058/program-not-outputting-the-correct-standard-deviation-also-problems-with-valid – Galik Nov 12 '18 at 17:10

1 Answers1

0

One possibility is to use a std::istringstream to get individual words on each line. When iterating over each word, increment a counter that keeps track of how many words have been processed.

If you need to process the second word on each line, you must check if the counter value is equal to 1 (assuming that when moving to a new line, the counter is initialized to 0).

Since you mentioned that you can check if a given string is a number, I have not provided with an implementation for the isNumber() function.

Below there is some source code that prints each line + each word, 'simulating' the call to your isNumber() function, for each second word (on each line of input).

#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;
}
Polb
  • 640
  • 2
  • 8
  • 21