I am trying to learn basic C++ after being a Java developer. So I decided to give CLion a try. I wrote this basic code just to familiarize myself with some C++ syntax.
#include <iostream>
using namespace std;
int main() {
string word;
cout << "Enter a word to reverse characters: " << endl;
getline(cin, word);
for(int i = word.length(); i != -1; i--) {
cout << word[i];
}
return 0;
}
The code is functional. It reverses whatever word you input. I wanted to step through it to see variables and what not, and to test out CLion's debugger.
My problem occurs when I get to
getline(cin, word);
When I step onto this line, I enter a word and hit enter. Then step over. After I do this nothing happens; all the step over, in, etc. buttons are disabled. I am unable to continue through the loop, or run the remainder of the code.
I have used Eclipse's debugger many times for Java development without any issues. Any ideas could be helpful.
TL;DR How do I step through a C++ command line program with basic input and output using CLion?
I've replicated the problem - looks to me like when debugging the newline is being swallowed by the IDE and not passed back to the program. I've submitted a bug to JetBrains. I don't see a way to work around this aside from getting out of the IDE and debugging directly with GDB or another IDE.
UPDATE: This issue was fixed in the Clion EAP Build 140.1221.2. It even made the first change listed in the release notes:
The most valuable changes are:
Debugger doesn’t hang on ‘cin >>’ operator any more.
Looking at your code, if everything is correct, you need to add #include <string>.
When I run this, it compiles and completes the output.
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter a word to reverse chars: ";
std::getline(std::cin, word); //Hello
for (int i = word.length() - 1; i != -1; i--) {
//Without - 1 " olleh"
//With - 1 "olleh"
std::cout << word[i];
}
std::cout << std::endl;
system("pause");
return 0;
}
Use the following code. I have modified your code to make it workable for your purpose. :)
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
cout << "Enter a word to reverse characters: " << endl;
getline(cin, word);
for(int i = word.length() - 1; i != -1; i--) {
cout << word[i];
}
printf("\n");
system("pause");
return 0;
}
Related
Currently doing a project at uni where at first I need to de-hyphenate a string, seemed pretty simple however when i run the program it has an error WeirdPuncProgram.exe: Microsoft C++ exception: std::out_of_range at memory location 0x004EF898
It also is not returning the string value properly, inside the function answer() is changed and hyphens are removed but once it comes out its just the original input again.
#include <iostream>
#include <string>
using namespace std;
string answer;
string hyphonRemover(string answer)
{
string spacer = " ";
int h;
for (int i = 0; i < answer.length(); i++)
{
h = answer.find_first_of("-");
answer.replace(h, 1, spacer);
}
return answer;
}
int main()
{
cout << "Type a sentence which contains punctuation and ill remove it for you! " << endl << endl;
getline(cin, answer);
hyphonRemover(answer);
cout << answer << endl;
system("pause");
return 0;
}
every use of answer in hyphonRemover() will be local variable, not global answer you defined above.
thus the function will modify only its local variable.
I'm new to C++. I stumbled upon one tutorial problem, and I thought I'd use the few things I have learnt to solve it. I have written the code to an extent but the code exits at a point, and I really can't figure out why. I do not want to go into details about the tutorial question because I actually wish to continue with it based on how I understood it from the start, and I know prospective answerers might want to change that. The code is explanatory, I have just written few lines.
Here comes the code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double average_each_student() {
cout << "\n>Enter your scores seperated by spaces and terminated with a period\n"
<< ">Note: scores after total number of six will be truncated.\n"
<< endl;
double sum = 0, average = 0;
int user_input, counter = 0;
const double no_of_exams = 6;
while(cin >> user_input) {
++counter;
if(counter < 5) sum += 0.15 * user_input;
else if(counter > 4 && counter < 7) sum += 0.20 * user_input;
}
return sum / no_of_exams;
}
int reg_number() {
cout << "Enter your registration number: " << endl;
int reg_numb;
cin >> reg_numb;
return reg_numb;
}
int main() {
vector<int> reg_num_list;
vector<double> student_average;
reg_num_list.push_back(reg_number());
student_average.push_back(average_each_student());
string answer;
cout << "\n\nIs that all??" << endl;
//everything ends at this point.
//process returns 0
cin >> answer;
cout << answer;
}
The code exits at cout << "\n\nIs that all??" << endl;. The rest part after that is not what I intend doing, but I'm just using that part to understand what's happening around there.
PS: I know there are other ways to improve the whole thing, but I'm writing the code based on my present knowledge and I wish to maintain the idea I'm currently implementing. I would appreciate if that doesn't change for now. I only need to know what I'm not doing right that is making the code end at that point.
The loop inside average_each_student() runs until further input for data fails and std::cin gets into failure state (i.e., it gets std::ios_base::failbit set).
As a result, input in main() immediately fails and the output of what was input just prints the unchanged string. That is, your perception of the program existing prior to the input is actually wrong: it just doesn't wait for input on a stream in fail state. Since your output doesn't add anything recognizable the output appears to do nothing although it actually prints an empty string. You can easily verify this claim by adding something, e.g.
std::cout << "read '" << answer << "'\n";
Whether it is possible to recover from the fail state on the input stream depends on how it failed. If you enter number until you indicate stream termination (using Ctrl-D or Ctrl-Z on the terminal depending on what kind of system you are using), there isn't any way to recover. If you terminate the input entering a non-number, you can use
std::cin.clear();
To clear the stream's failure stated. You might want to ignore entered characters using
std::cin.ignore(); // ignore the next character
or
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ignore everything up to the end of the line
use cin.clear(); before cin >> answer; That will fix the problem. But you are not controlling the input. it just runs out to cin..
I've been wondering how to go about running a program within another program where the the main process can output into the stdin of the secondary process as well as have that second process output to the input to the primary one.
The closest I have come to finding a term for this idea is pipes and forks but I don't quite get the examples i've seen. I've only seen ones where the same program is using pipes to launch itself again. Additionally all of these examples assume that that the programmer is writing/has access to both program's source code.
I would like to be able to interface in this way with programs that are already compiled. Here's an example of what I would like to be able to do:
This is the "compiled" program-
#include <iostream>;
using namespace std;
int main(){
int answer = 42;
int guess = 0;
do{
cout << "Guess a number..." << endl;
cin >> guess;
if(guess<answer)
cout << "Guess Higher!" << endl;
else if(guess>answer)
cout << "Guess Lower!" << endl;
}while(answer!=guess);
cout << "You win!";
return 0;
}
This is the "parent" program-
#include <iostream>;
using namespace std;
int main(){
//Code executing and connecting the other program
//while cin/cout would be nice for keeping it clean, other methods of doing this are fine
//I used cin/cout as placeholders to try and make what I am asking clearer
String out;
cin >> out;//Load initial prompt
int high=100, low=0;
do{
cout << (high+mid)/2 << endl;
cin >> out;//Load response
if(out.compare("Guess Higher!"))
low = (high+low)/2;
else
high = (high+low)/2;
}while(out.compare("You win!")!=0);
return 0;
}
The idea here is that my "parent" program could play this game for me. It would make a guess, view the response, use some logic to decide what to do next, guess, repeat until it wins. This particular example is pretty useless but the same general idea of controlling one program with another has a lot of uses. This is just a hypothetical demo of would I would like to be able to do.
Thanks to anyone kind enough to take time out of their day to help.
i am trying to develop a program that it waits for particular period of time for input and comes out after some time in c++ ,like we do in atm machine .
can anyone try to help me.
#include <iostream>
#include <ctime>
#include<string>
using namespace std;
int main(){
string name;
cout << "Enter your name: ";
int endTime= 5;
int i=0;
// cout<<endTime<<endl;
while(i < endTime)
{
getline(cin, name);
i++;
endTime--;
if( i > endTime && (name.empty()))
break;
}
cout << "NO NAME ENTERED!!" << endl;
Part of your problem is that getline() is a blocking call, and won't return until someone inputs something.
What you could do is to research threading - have two different threads, one of which has the sole responsibility to watch time, and if the time has passed, then you send a signal to kill the other thread.
You are limited a lot by the input method that you showed here.
I'm currently working on the book "C++ Primer Plus" and doing some of the programming excersis.
As it seems, I'm having a problem with Xcode(4.3.3) because following code doesn't work how it's supposed to work:
#include <iostream>
#include <string>
struct car
{
std::string maker;
int year;
};
int main()
{
using namespace std;
cout << "How many cars do you wish to catalog? ";
int nCars;
(cin >> nCars).get();
car* aCars = new car[nCars];
for (int i = 0; i < nCars; i++)
{
cout << "\nCar #" << (i + 1) << endl;
cout << "Please enter the make: ";
getline (cin, (aCars + i)->maker);
cout << "\nPlease enter the year made: ";
(cin >> (aCars + i)->year).get();
}
cout << "Here is your collection: \n";
for (int i = 0; i < nCars; i++)
{
cout << (aCars + i)->year << " " << (aCars + i)->maker << endl;
}
delete [] aCars;
return 0;
}
The problem is, I don't have the chance to enter any maker. The program directly goes to the point where I have to enter the year, even though I'm using "(cin >> nCars).get();" to get rid of the newline character.
Am I overlooking something?
Thanks in advance!
I suspect that you may be running on windows and the two-byte newlines are hitting you. You may be able to improve things (for lines that aren't ridiculously long) with ignore:
cin >> nCars;
cin.ignore(1024, '\n');
Note that since you rely on stream numeric processing, entering a non-numeric year such as QQ will result in the programming just finishing without asking for any more input.
You don't need to do math on the years so treat them as strings instead of integers. Then if you need to you can do validation of each year after you get the input.
Ok, guys..I found the problem.
The console within Xcode doesn't work as expected when using cin.get().
I tried the same code in the terminal as well as with Visual Studio (Win 7) and the program works perfectly.
Anyway, thank you all for your advices. I'll try consider them the next time. :)
Cheers!