Edit 2:
Well, turns out I was just being dumb! It wasn't anything to do with the code at all. I was running everything via a bash script, and because of how I was using it before (which also didn't require any input) I was still running it with & at the end - so obviously I couldn't get any input from that shell.
My program seemingly skips the line were I try to receive input using cin (it goes right to the next line).
Edit: Please look at the bottom where I put the new code and what happens.
I've searched here and googled, and I've found a lot of questions where people had the same problem! As far as I understand, the problem was almost always a leftover '\n' - but none of the solutions have worked for me sofar. This is the problematic code:
//char input_char;
std::string input_string;
//int input_int;
//std::string line;
std::cout << "hello. your input: ";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
std::cin >> input_string;
// std::getline(std::cin, input_string);
std::cout << "input: " << input_int << endl;
I only need one character or number. I've tried it with a character, int, or string; and I've tried cin and getline. I've added clear and ignore as was suggested for other similar questions, but I still have the same problem.
This is at the beginning of my main, so I'm not doing any other cout or cin before this code. However, this is part of a larger project, and I'm using ros. Before the program gets to this part, there are other outputs which are handled through ros; no other input though.
I'd very much appreciate you help with this! I feel like I must be missing something really obvious...
Edit: I've now commented out literally everything that isn't immediately related to this input, and moved cin to the very top of the main. This is now the complete code (commented parts left out):
#include <iostream>
#include <ros/ros.h>
#include <vector>
#include <ros/console.h>
#include "std_msgs/String.h"
//#include <SharedMessages/MicroconRequest.h>
/* ... */
//ros::Publisher reqPublisher;
//SharedMessages::MicroconRequest reqMsg;
/* ... */
int main( int argc, char* argv[] )
{
char input_test;
std::cout << "character: ";
std::cin >> input_test;
std::cout << input_test;
std::cout << "did that work?";
// Handle ROS communication
ros::init( argc, argv, "Gestures" );
ros::NodeHandle n;
//ros::Subscriber joy_sub_ = n.subscribe<sensor_msgs::Joy>("joy", 10, joyCallback, this);
//reqPublisher = n.advertise<SharedMessages::MicroconRequest>("MicroconRequest", 10);
ros::Rate loop_rate(10);
// Infinite control loop
while (ros::ok())
{
/* ... */
cntLoop++;
ros::spinOnce();
loop_rate.sleep();
}
// turn off microcontroller
return 0;
}
Now what happens is the following:
$ ./startDemo.bash
Starting Minimal Example
$ character: a # now I have time to input something, but...
a: Befehl nicht gefunden. # = command not found]
# then it doesn't do anything, so I stop it
$ ./stopDemo.bash
killing /Gestures
did that work?[ WARN] [1473954737.268901991]: Shutdown request received.
[ WARN] [1473954737.268978735]: Reason given for shutdown: [user request]
killed
$
Only after killing the program does the output suddenly appear. What is happening here? I'm so confused.
I don't understand your original question about skipping a line but the reason nothing is printed until you shutdown is that you are missing the endl from the output. I added it and the output seems as you would expect?
char input_test;
std::cout << "character: ";
std::cin >> input_test;
std::cout << input_test;
std::cout << "did that work?" << std::endl;
Output:
root#93043381199d:/catkin_ws/devel/lib/stack# ./stack_node
character: a
adid that work?
Well, turns out I was just being dumb! It wasn't anything to do with the code at all:
I was running everything via a bash script, and because of how I was using it before (which also didn't require any input) I was still running it with & at the end - so obviously I couldn't get any input from that shell.
[Note: I wasn't sure if it was good practice to answer one's own question; at first I just edited it. But I figured it'd make more sense than to just leave it open.]
Related
I am right now learning about making a program using Borland, so this is my first time on use it. I got confused by the result, cause the result is not what I expected.
Below is my code:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char nama[25];
char kelas[5];
char jurusan[30];
char universitas[30];
char alamat[30];
cout<<"Masukkan Nama Anda\t : ";
gets(nama);
cout<<endl;
cout<<"Kelas\t\t\t : ";
gets(kelas);
cout<<endl;
cout<<"Jurusan\t\t\t : ";
gets(jurusan);
cout<<endl;
cout<<"Universitas\t\t : ";
gets(universitas);
cout<<endl;
cout<<"Alamat\t\t\t : ";
gets(alamat);
cout<<endl;
cout<<"\n\tBIODATA ANDA SEBAGAI MAHASISWA ADALAH SEBAGAI BERIKUT:"<<endl;
cout<<"\n\nNama\t\t\t : "<<nama<<endl;
cout<<"Kelas\t\t\t : "<<kelas<<endl;
cout<<"Jurusan\t\t\t : "<<jurusan<<endl;
cout<<"Universitas\t\t : "<<universitas<<endl;
cout<<"Alamat\t\t\t : "<<alamat<<endl;
cout<<"\n\nSilahkan tekan tombol ENTER untuk keluar dari program biodata singkat ini!";
getch();
}
The result I got is kinda fine, but there is still one problem that I got here. Which there is one variable that don't show what the value of the user already gave, it did not show the value, it even just gave the word "u" which I don't understand from where this word was coming. I sent it with my picture, so you can see it.
I hope you would help me, and thank you very much for reading my problem.
All of your input arrays:
char nama[25];
char kelas[5];
char jurusan[30];
char universitas[30];
char alamat[30];
are going to be one continuous block of chars. Your input methods will easily overflow from one array to the next causing all sorts of havoc.
Try using std::string instead and input from std::cin:
std::string nama;
std::string kelas;
std::string jurusan;
std::string universitas;
std::string alamat;
std::cout << "Masukkan Nama Anda\t : ";
std::cin >> nama;
std::cout << std::endl;
std::cout <<"Kelas\t\t\t : ";
std::cin >> kelas;
std::cout << std::endl;
std::cout << "Jurusan\t\t\t : ";
std::cin >> jurusan;
std::cout <<std::endl;
std::cout << "Universitas\t\t : ";
std::cin >> universitas;
std::cout <<std::endl;
std::cout << "Alamat\t\t\t : ";
std::cin >> alamat;
std::cout << std::endl;
After i tried some several suggestion to solve my own problem. Then i wonder, why there is just the variable of Jurusan which contain character that i don't know where it comes from. I tried to see it again, and then i reverse the place of another variable, also i put a comment sign //comment to make it not being seen as a code by machine in front of the Jurusan variable there is no problem anymore. Quite thinking, and then i just tried to count the sum of character in a variable which exactly below the Jurusan variable(Universitas variable), and then i also count the size of that variable(Universitas variable).
After this i just realised if the word "u" which in the variable Jurusan is the rest of the characther which comes from the variable below the Jurusan variable, which variable Universitas.
I am as the user, put the characther greater than the size of Universitas variable. And of course, that is wrong, and a mistake.
I came back to the code, and make the size of the variable Universitas is greater than before, and right now the problem is solved. And you guys can see it in my picture below if that is already succed, you also can compare it with the previous picture that i sent here in the Question section which has problem.
So, thank you guys for you who tried to help me. Cheers!
Here is an example code demonstrating the problem I'm facing.
#include <iostream>
#include <string>
extern "C" {
#include <unistd.h>
}
int main()
{
std::cout << "Making tests ready!" << std::endl;
std::cout << "\nTo start out, Enter an integer: ";
int a = 0;
std::cin >> a;
std::string input;
sleep(3); // what to do if user enters data during this?
std::cout << "\n Now enter a string";
std::getline(std::cin, input);
std::cout << "\nHere are your values - " << a << " & " << input;
return 0;
}
See the sleep call in between the code? This could be replaced with somewhat long delays while computing something when my program isn't accepting any inputs. Now if user presses some keys during this time, that input is captured by std::getline() in next line of code. I know this is the default behavior since it should capture the input being provided.
But what I want is to clear all that captured input and start fresh with 15th line that is std::cout << "\n Now enter a string";, which is immediately after sleep. I don't know exact term to describe this or else I would have used that. Thanking you.
Edit: I've tried using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); in my code, but it asks for input and then discards it.
Please mind my english, not a native speaker.
Reading the comments causes me to think that you can't really solve this problem (at least by the means suggested there). There's an inherent race condition in any case. Consider the following lines:
sleep(3);
// (*) <- Potential location 1.
std::cout << "\n Now enter a string";
// (**) <- Potential location 2.
std::getline(std::cin, input);
The various comments show some (very technically-competent) ways to flush the standard input. The problem is, you cannot put them in the location marked (*) nor (**).
First location - you clear the standard input some way. Now you decide it's time to move to the next line (std::cout << ...). While you do that, the user types in some more input. Race!
Second location - You print out the message (std::cout << ...), and proceed to clear the standard input. Before you manage to do that, the user typed in something. Race!
It seems to me that any of the techniques described in the comment require locking the standard input, and I don't think there's a (standard) way to do so.
Why does trying to input two strings using cin.get() fails? I can successfully read the first string but the input fails for second string and subsequent operations.. See the code:
#include <iostream>
#include <stdlib.h>
int main(){
long int n,k;
char a[11],b[11];
cin.get(a,11);
n = atoi(a);
cin.get(b,11);
cout<<b;
k = atoi(b);
cout << "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good() << endl << endl;
}
I am trying to input two strings and store them into long int variables as shown in program, but the cin.get(b,11) fails and stack overflow occurs for
k= atoi(b) .Also, you may observe nothing is output for cout<<b .. And, at last cin.fail() is set to 1 , which means I am doing some kind of logical error.. Please help me in rectifying this!
Please suggest some method which is fast and meant for c++ only ..
(If you feel this question is too bad please mention in comments before down voting this, I am already struggling at 21 rep!)
\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get()
cin.get(a,11);
n = atoi(a);
cin.get();
cin.get(b,11);
cout<<b;
k = atoi(b);
cin.get() Does not extract the delimiter from the input (documentation).
If you are C++ with streams it makes sense to use the built in functionality. In particular, C++ offers formatted I/O. To read two numbers you should use:
long int a, b;
cin >> a;
cin >> b;
This will read two numbers from the standard input.
If speed is a concern, try to turn off C I/O synchronisation: std::ios::sync_with_stdio(false); There is an interesting benchmark here that shows that if you turn of synchronisation with C I/O, streams are actually pretty fast.
I am not so sure how the works I suppose is my root problem here. I've read a few previous posts on while(cin>>x) but nothing seems to answer my question really.
I am using this loop to read in some text data:
while (cin >> x){
searchText.push_back(x);
}
but then later in the code I am trying to read in a single word using:
cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;
but the above while loop/ eof seems to scupper the 2nd code snippet (if I move the 2nd code snippet up above it all works fine, but obviously that is not what im trying to do)
EDIT
Here is the full code for clarity:
int main()
{
// ask for the target word
// cout << "Please enter your target word: ";
// string targetWord;
// cin >> targetWord;
// ask for and read the search text
cout << "Enter the complete search text, "
"followed by end-of-file: ";
vector<string> searchText;
string x;
while (cin >> x){
searchText.push_back(x);
}
// check that some text was entered
typedef vector<string>::size_type vec_sz;
vec_sz size = searchText.size();
if (size == 0){
cout << endl << "You must enter some text. "
"Please try again." << endl;
return 1;
}
// ask for the target word
cin.clear();
cout << "";
cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;
int count = 0;
for (int i=0; i<size; ++i){
if (targetWord == searchText[i]){
count++;
}
}
cout << "The target word [" << targetWord << "] was "
"in the search text " << count << " times." << endl;
return 0;
}
I am just trying to take in some text from the user... then a search word and see how many times the word appears in the entered text (pretty simple!)
I know I could do it differently but the question here is more about how can I use the cout/ cin stream again after it has had an EOF in it previously
When cin (or any other std::stream) hits an end of file, it sets a status to indicate that this has happened.
To reset this status, you need to call cin.clear();, which will clear any "bad" state, and make sure the stream is "ok" to use again. This also applies if you are reading from a file, and want to restart from the beginning.
Edit: I just took the code posted above, and ran it on my machine, adding at the top
#include <iostream>
#include <vector>
using namespace std;
This following is the compile and run:
$ g++ -Wall words.cpp
words.cpp: In function ‘int main()’:
words.cpp:40:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
$ ./a.out
Enter the complete search text, followed by end-of-file: aa bb cc [CTRL-D]
Please enter your target word: aa
The target word [aa] was in the search text 1 times.
which is what I expected to see...
Edit2: For completeness: The "success rate" of using cin.clear() will depend on the implementation. A more reliable solution is to use a different way to mark the end of the stream of words in the first phase of the program. One could use a single "." or "!" or some other thing that isn't supposed to be in a "word" - or something longer, such as "&&#&&", but that makes it hard to type and remember when one is 15 pages into the input.
When execution leaves the loop
while (cin >> x){
searchText.push_back(x);
}
it does so because the "testing" of cin has returned false, in other words, failbit and/or badbit has been set on the stream. When that is the case, any further attempt to read from the stream will fail, i.e. targetWord will be left empty.
To make the stream usable again, you have to reset the error flags by calling cin.clear();
It would be somewhat helpful if we knew the type of x in the
first loop, but basically: you read all of the available input,
then try to read some more, and you're surprised that it's
failing. The contrary would surprise me.
The real question is: what are you trying to do? Basically,
what is the type of x, and—I'm assuming that you're
supposing that cin is an interactive device because of the
prompt—how do you determine that the first input has
finished? If the first loop ends because of "end of file" (user
entered control-D under Unix, or control-Z under Windows), then
there's no way you can reliably expect to read more. Resetting
the error status with cin.clear() might work; it will cause
the istream to try to read more from the streambuf. But it
might not; there are any number of layers below the istream
which, for whatever reason, may have memorized the end of file.
So you'll have to find some different way of recognizing the
end.
Just guessing from the names of the variables: if you're trying
to read a list of words, I'd use std::getline, with an empty
line for the end of the list. So the first loop would become:
while ( std::getline( std::cin, x ) && x != "" ) {
searchText.push_back( x );
}
if ( ! std::cin ) {
// Something really bad has happened...
}
Alternatively, you might want to break up the line on white
space, to allow more than one word per line (and to ignore any
extra white space in the line:
std::string line;
while ( std::getline( std::cin, x ) && x != "" ) {
std::istringstream l( line );
while ( l >> x ) {
searchText.push_back( x );
}
}
if ( ! std::cin ) // ...
Even if x has some other type, you might want to consider
something along these lines.
I used cin.clear() and on my mac set-up it did not seem to clear the EOF but on a ubuntu set-up it did clear the stream
Apple:
(Canopy 32bit) joes-imac:chap3 joe$ g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
Ubuntu:
joe#joe-HPlaptop:~$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
I am happy to accept it is just compiler differences and finish/ close the issue (was a silly little one really!)
Thanks for all the help though (my first stackoverflow question actually!)
cin will stop when it will encounter endline character or a newline. So every time you enter something and hit enter it you are providing an '\n'. while(cin>>x){} should be used to read input continuously without endline/'\n'.
I know this is a noob question. I used this example code from here. How is it supposed to work? I thought you can input something for who but it just closes immediately.
#include <iostream>
#include "getopt_pp_standalone.h"
using namespace GetOpt;
using namespace std;
int main(int argc, char* argv[])
{
string who;
GetOpt_pp ops(argc, argv);
ops >> Option('n', "name", who, "world" ); /* the default name is 'world' */
cout << "Hello " << who << "!" << endl;
return 0;
}
Variants of getopt get options from the command line rather than input by a user.
You will need to run your program with something like:
myprog -n Pax
If you want interactive input from the user, get rid of the getopt stuff altogether and just use the streams, such as:
std::cout << "Identify yourself, interloper!\n";
std::cin >> who;
std::cout << "Hello, " << who << ", my name is Pax.\n";
A few other things to impart:
First, you may need to put a getchar() (or cin >> who) before the return if you're running in an IDE that closes the execution window instead of waiting. Otherwise, the output will go to the window and immediately disappear.
Second, while it's probably okay for small programs, using namespace std can cause problems with more substantial projects (in terms of polluting the standard namespace, see here for a good explanation). I prefer to fully qualify my calls, such as:
std::cout << "blah, blah, blah\n";
Third, endl is used far too often by most developers. Most times you should just either use '\n' instead, or just tack on \n to the end of a string like "Hello, world!\n". That's because the \n way doesn't force possibly inefficient flushing of the stream like endl does. That's covered here.