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