Read in numbers from console won't stop at newline.


 
Thread Tools Search this Thread
Top Forums Programming Read in numbers from console won't stop at newline.
# 1  
Old 11-24-2017
Read in numbers from console won't stop at newline.

Hello,
I have snippet code from Lippman's <<C++ primer>>.
The program is to convert regular decimal (0 ~ 15) numbers to basic hexdecimals. The instruction tells the program will execute by hitting newline at the end. When I tried to run the compiled program, hitting ENTER did not work as instructed in the book. I have to hit any invalid letter/key or Ctrl+D (I'm using Ubuntu) to terminate the input.
Code:
#include <iostream>
#include <string>

using namespace std;

int main ()
{
  const string hexdigits = "0123456789ABCDEF";    //All possible hex digits
  cout << "Enter a series of numbers between 0 and 15"
    << " separated by spaces.\nHit ENTER when finished: " << endl;

  string result;        //will hold the resulting hexify-ed string
  string::size_type n;        //hold numbers from the input

  while (cin >> n)
    if (n < hexdigits.size())    //ignore invalid input
      result += hexdigits[n];    //fetch the individual hex digit

  cout << "Your hex number is: " << result << endl;
  return 0;
}

Exact same question was asked in stackoverflow,

Code:
// https://stackoverflow.com/questions/19307979/cin-in-a-while-loop
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main ()
{
  const string hexdigits = "0123456789ABCDEF";

  cout <<  "Enter a series of numbers between 0 and 15"
       << " separated by spaces. Hit ENTER when finished: "
       << endl;

  string line;
  string result;

  if (getline (cin, line))    // get the whole line
    {
      istringstream iss(result);    // break them by spaces
      int i;
      while (iss >> i)
    {
      result += hexdigits[i];
      result += " ";
    }
      cout << "Your hex result:  " << result << endl;
    }
  else
    {
      cout << "Error handling input!" << endl;
    }

  return 0;
}

1) which used getline() and I can't get the logic flow and the posted code did not work as expected; and
2) it seems there may be better way for this basic trick.
My question is what is the best practice to stop reading space-delimited numbers at newline instead of Ctrl+D or by hitting any invalid char?
Thanks!

Last edited by yifangt; 01-24-2018 at 05:24 PM.. Reason: typos and reformat
# 2  
Old 11-24-2017
The >> operator does not care at all about lines. If you want lines, you'll have to separate it some other way, which is exactly what the stackoverflow code does.

It reads entire lines with getline, then crams the entire line into a stringstream object. A stringstream, unlike standard input, will just hit EOF when it runs out of data instead of waiting for more.
These 2 Users Gave Thanks to Corona688 For This Post:
# 3  
Old 11-27-2017
Thanks Corona688!
I did not forget your advice on fgets() + sscanf() in C. Switched from there I was hoping to get similar advice in C++ so that I used "best practice". I am aware this is about very basic I/O stream that I'm still struggling with.
Spend more time on this, and found out my confusion also related to this line of the stackoverflow code, which seems wrong to me:
Code:
istringstream iss(result);  // break them by spaces, Wrong code!!
istringstream iss(line);    //This gave me what I expected.

My question seems answered.
Thanks again!

Last edited by yifangt; 01-24-2018 at 05:26 PM.. Reason: Formating to get better view
This User Gave Thanks to yifangt For This Post:
# 4  
Old 11-27-2017
It's the exact same problem as fgets, too.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

While read won't run keyboard function

I am using while read do/ done to retrieve menu item. Works as advertised, no problem. I am using this hack function "pause" to stop script execution and wait for keyboard "enter" key to continue. Sort of break point function. Also works fine with one exception - it does not work when used... (4 Replies)
Discussion started by: annacreek
4 Replies

2. HP-UX

CDE Login on console won't use keyboard

Hi all, I'm installing a HP r2660 machine with HP-UX 11.23 (this version fixed by customer's product) and I've troubles using the VGA console as workstation display. At first it worked just as TEXT console, then I fixed /etc/dt/config/Xservers and now I've the CDE prompt for login. ... (5 Replies)
Discussion started by: larry100
5 Replies

3. Shell Programming and Scripting

Loop to read parameters and stop

Hey guys, How do I make a loop that reads all the parameters en then stop when there are no parameters anymore ? Something that gives an output like this: ./Script.sh parameter1 parameter2 parameter3 parameter = parameter1 parameter = parameter2 parameter = parameter3 Thanks a lot,... (5 Replies)
Discussion started by: Miki1579
5 Replies

4. Shell Programming and Scripting

Read Embedded Newline characters with read (builtin) in KSH93

Hi Guys, Happy New Year to you all! I have a requirement to read an embedded new-line using KSH's read builtin. Here is what I am trying to do: run_sql "select guestid, address, email from guest" | while read id addr email do ## Biz logic goes here done I can take care of any... (6 Replies)
Discussion started by: a_programmer
6 Replies

5. Shell Programming and Scripting

Null Handling in Until loop. . .loop won't stop

Hi Im running this script, which is supposed to find the max value build some tables and then stop running once all the tables are built. Thing is , it keeps assigning a null value to $h and then $g is null so it keep building tables i.e. testupdateNUL. How can I stop this? Here is what I have: ... (4 Replies)
Discussion started by: brandono66
4 Replies

6. UNIX for Dummies Questions & Answers

how to stop the message on the console

Hi, Sun Solaris. I am working on the console, I have pulled the network cable out. I am in the process of changing the IP address and few others thing. But this message comes every few seconds. SUNW,hme0: Link Down - cable problem? SUNW,hme0: Link Down - cable problem? It's very... (2 Replies)
Discussion started by: samnyc
2 Replies

7. Shell Programming and Scripting

read numbers from file and output which numbers belongs to which range

Howdy experts, We have some ranges of number which belongs to particual group as below. GroupNo StartRange EndRange Group0125 935300 935399 Group2006 935400 935476 937430 937459 Group0324 935477 935549 ... (6 Replies)
Discussion started by: thepurple
6 Replies

8. Solaris

Red stop signs in Solaris Management Console 2.1

I've installed Solaris 10 (x86 8/07) on a Dell PowerEdge 2950. When I bring up the Solaris Management Console I get red stop sign looking icons on all areas (System Status, System Configuration, Services, Storage, and Devices and hardware) under This computer. Originally nothing was showing up... (1 Reply)
Discussion started by: kayroreality
1 Replies

9. Shell Programming and Scripting

read from console in ksh

I am stuck with a problem while reading data from a file.. while do read line #do some operations and if some condition is satisfied, ask the user to enter his choice. # using the choice continue operations. done < fileBeingRead.txt The... (4 Replies)
Discussion started by: ajaykumarns
4 Replies

10. Shell Programming and Scripting

Script does not stop when doing a read

Hi Folks, I have been trying to create a script wherein after it reads a certain number of data, it will pause and ask the user if he wants to continue or not. However, it seems that when it is supposed to read the user's answer, the script will go into a loop. What is wrong with my script here?... (7 Replies)
Discussion started by: rooseter
7 Replies
Login or Register to Ask a Question