0

I want to read some lines from keyboard and for every line, I want to split it into multiple numbers and to convert these numbers to integers.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
using namespace std;

#define NO_LINE_TO_READ (1u)


std::string string_to_hex(const std::string& input)
{
   
    static const char hex_digits[] = "0123456789ABCDEF";

    std::string output;
    output.reserve(input.length() * 2);
    for (unsigned char c : input)
    {
        output.push_back(hex_digits[c >> 4]);
        output.push_back(hex_digits[c & 15]);
    }
    return output;
}



int main() {
    string line;
    std::vector<int> v;
    int sum = 0;
    static uint8_t no_line = 1u;
    istringstream iss;
    for (; (no_line <= NO_LINE_TO_READ) && (std::getline(std::cin, line)); ++no_line) 
    {
        iss.clear();
        iss.str(line);
        string S;
        while (iss)
        {
          iss >> S;     
          //v.push_back(stoi(S));
          //std:: cout << stoi(S);
          std::cout << "Displaying S: " << S << endl;   
          std::cout << "Displaying hex value of: " << S << " (char)"<< endl;
          std::cout << "0x" << string_to_hex(S) << endl;
          S.clear();
        }
    }
       
    return 0;
}

I think the problem is here:

iss.clear();
iss.str(line);
string S;
while (iss)
{
  iss >> S;     
  //v.push_back(stoi(S));
  //std:: cout << stoi(S);
  std::cout << "Displaying S: " << S << endl;   
  std::cout << "Displaying hex value of: " << S << " (char)"<< endl;
  std::cout << "0x" << string_to_hex(S) << endl;
  S.clear();
}

Because if I enter this line
4 5 6
from the keyboard, the program displays the following result:

_**Displaying S: 4 <br />
Displaying hex value of: 4 (char) <br />
0x34 <br />
Displaying S: 5 <br />
Displaying hex value of: 5 (char) <br />
0x35 <br />
Displaying S: 6 <br />
Displaying hex value of: 6 (char) <br />
0x36 <br />
Displaying S:  <br />
Displaying hex value of:  (char) <br />
0x**_

If I look at the last three lines, it looks like _**while(iss)**_ executed in addition with one step and I can't pass _**S**_ to _**stoi**_ function.

Unfortunately, I do not understand very well how internally is working the operator >> for istringstream and I can not figure out how I could solve the problem so that the last three lines do not appear.

0 Answers0