I have been working on this program for a while and I finally got rid of the compile errors. But when I tried it, the program basically skipped a line of code.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main(){
string nameOfFile = "";
char index;
char title[100];
char name[100];
char copyright[100];
cout << "Welcome, and hello to the html templating software" << endl;
cout << "Is this your index page?\ny/n" << endl;
cin >> index;
if (index=='n'){
cout << "Enter the prefered name of this file" << endl;
getline(cin, nameOfFile, '\n');
}
cout << "What will the title of the page be?" << endl;
cin.getline(title, 100);
cout << "What is your name?" << endl;
cin.getline(name, 100);
cout << "What is the copyright?" << endl;
cin.getline(copyright, 100);
cin.get();
return 0;
}
You see how after asking if this is your index page it skips the next cin.getline function no matter the scenario.
When the user entered the index, they also typed a newline, but your cin didn't remove it from the input stream. So, your call to cin.getline returns immediately because of the leftover newline.
Add a call to cin.ignore before the cin.getline to flush it out.
replace getline(cin, nameOfFile, '\n')
with
cin >> nameOfFile
Related
I have a code from my friend and we do not know how to use cin. ignore very well.
Our problem is that we are using do while and at the end of loop we want to ask user to enter if he wants to again enter some values as you will see from the code itself.
If the answer is 'y' then he can "write" again but the problem is we are using getline and we have the problem with the first getline in this loop. The program does not recognise it after the first time use.
Here is the code:
int main() {
ofstream datoteka("podaci.txt", ios::app);
if (datoteka.fail()) {
cout << "Ne postojeca datoteka";
exit(1);
}
string ime;
string prezime;
char pol;
int godiste;
float prosjek;
char odluka;
do{
system("CLS");
cout << "Unesite ime: ";
getline(cin, ime);
datoteka << ime;
cout << "Unesite prezime: ";
getline(cin, prezime);
datoteka << " " << prezime;
cout << "Unesite pol(M - musko, Z - zensko): ";
cin >> pol;
datoteka << " " << pol;
cout << "Unesite godiste: ";
cin >> godiste;
datoteka << " " << godiste;
cout << "Unesite prosjek: ";
cin >> prosjek;
datoteka << " " << prosjek << endl;
cout << endl;
cout << "Da li zelite unijeti podatke za jos jednu osobu?" << endl;
cout << "[Y] za da, [N] za ne : ";
cin >> odluka;
} while (odluka != 'N' || odluka !='n');
The problem is with the
getline(cin,ime);
It wont recognize it after the first time use.
Can someone help me?
The basic problem is that this code mixes two different forms of input. Stream extractors (operator>>) do formatted input; they skip whitespace, then try to interpret non-whitespace characters, and stop when they encounter something that doesn't fit with what they're looking for. That works fine when you have multiple extractors: std::cin >> x >> y >> z;,
getline() is an unformatted input function; it grabs whatever is in the input stream, up to the first newline.
If you mix them you can get into trouble. The usual way to get around this is to call some variation of cin.ignore() when you switch from formatted to unformatted input, and that's where the code in the question goes astray.
At the end of the loop, the code calls std::cin >> odluka;. That reads one character from the console, and leaves any additional input in place. Since the console itself typically will sit waiting for characters until it sees a newline character, typing that single character also requires hitting the Enter key, which puts a newline into the input stream. The extractor leaves the newline there. When the loop repeats, the code calls std::getline(std::cin, ime), which sees the newline character and stops reading input.
So whenever you transition from formatted input to unformatted input you have to clear out any remnants from the previous input efforts.
Or you can always read a line at a time, and parse the input yourself.
i'm not sure exactly what the problem is. i took your code and it does what it's supposed to be doing on my machine (made a few adjustments so i can understand what's going on):
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace::std;
int main() {
ofstream datoteka("podaci.txt", ios::app);
if (datoteka.fail()) {
cout << "Ne postojeca datoteka";
exit(1);
}
string ime;
string prezime;
char pol;
int godiste;
float prosjek;
// changed it to a char pointer
char odluka[] = { "Y" };
do{
system("CLS");
cout << "1: ";
getline(cin, ime);
datoteka << ime;
cout << "2: ";
getline(cin, prezime);
datoteka << " " << prezime;
cout << "3: ";
cin >> pol;
datoteka << " " << pol;
cout << "4: ";
cin >> godiste;
datoteka << " " << godiste;
cout << "5: ";
cin >> prosjek;
datoteka << " " << prosjek << endl;
cout << endl;
cout << "6" << endl;
cout << "[Y], [N]: ";
cin >> odluka;
// added this. it was not waiting for my input properly.
cin.get();
// print results
system("cls");
printf("results (press any key to move on)\n\n1: %s\n2: %s\n3: %c\n4: %d\n5: %.02f\n6: %c\n\n", ime.c_str(), prezime.c_str(), pol, godiste, prosjek, odluka);
getchar();
} while (_stricmp(odluka, "n")); // while "odluka" is not "n" or "N" (the _stricmp is not case-sensitive so they both return the same result)
system("cls");
printf("press any key to exit!\n");
getchar();
getchar();
}
here is the output from "podaci.txt":
test1 test1 1 1 1.1
test2 test2 2 2 2.2
consider using scanf/sprintf/printf with c strings in the future if this keeps malfunctioning perhaps?
I am wringing a simple code to learn more about string. When I ran my code it would not print my last name. Can someone explain why? I used string phrase to store it and it only appears to have stored my first name. Here is the code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting;
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
cin >> phrase;
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
I used string phrase to store it and it only appears to have stored my first name.
That makes sense.
cin >> phrase;
will stop reading when it encounters a whitespace character in the input.
To read the full name you can use one of the following approaches.
Use two calls to cin >>.
std::string first_name;
std::string last_name;
cin >> first_name >> last_name;
Use getline to read the entire line. getline will read everything in a a line, including whitespace characters.
getline(cin, phrase);
When you call cin >> phrase;, it only reads the string up to the first non-space character. If you want to include spaces in your name, best goes with getline(cin,phrase);.
IMPORTANT: getline() will reads whatever it is in the stream buffer up to the first \n. It means that when you enter cin >> greeting;, if you hit ENTER, getline() will read everything before that \n that is not already read, which is NOTHING into your phrase variable, making it an empty string. An easy way out is to call getline() twice. E.g.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting; //IMPORTANT: THIS ASSUME THAT GREETING IS A SINGLE WORD (NO SPACES)
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
string rubbish_to_be_ignored;
getline(cin,rubbish_to_be_ignored); //this is going to read nothing
getline(cin, phrase); // read the actual name (first name and all)
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
Assuming you store that code in the file stackoverflow.cpp. Sample run:
Chip Chip#04:26:00:~ >>> g++ stackoverflow.cpp -o a.out
Chip Chip#04:26:33:~ >>> ./a.out
Exercise 3B
Kaitlin Stevers
String arrays
Please enter a greeting:
Hello
The greeting you entered was: Hello
Enter your full name
Kaitlin Stevers
Hello, how are you today Kaitlin Stevers?
Tested on ubuntu 14.04
I am working on an assignment for my C++ class. The following code is given. The directions explain to enter a six character string and observe the results. When I do this, the second user prompt is passed over and the program ends. I am pretty certain the reason for this is that the first cin.getline() is leaving the extra character(s) in the input stream which is messing up the second cin.getline() occurrence. I am to use cin.get, a loop, or both to prevent the extra string characters from interfering with the second cin.getline() function.
Any tips?
#include <iostream>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
You are right. The newline character stays in the input buffer after the first input.
After the first read try to insert:
cin.ignore(); // to ignore the newline character
or better still:
//discards all input in the standard input stream up to and including the first newline.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will have to #include <limits> header for this.
EDIT:
Although using std::string would be much better, following modified code works:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
My code runs and works well the first time around, but I am having looping problems:
My code isn't counting characters that are in words
The second time around when you press "yes," it ends up printing everything out. I must have a loop in the wrong spot, but I can't find it for the life of me.
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
int cCount;
while(1) {
cout << "Enter a character to count the number of times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
cin >> sentence;
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = count(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << " " << cCount << " " << character << " " << "character(s)" << '\n';
}
cout << "Do you wish to enter another sentence (y/n)?: \n";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
By just reading your code, it looks fine, except where you get the sentence. Using cin, it will only read until it sees a newline or a space, so if you're entering a sentence, it will read every word as a different input.
Try getline(cin, sentence) and see if that fixes the problem.
Edit: Forgot to add in: use cin.ignore() after the getline. cin reads up to, and including the line break (or space) while getline only reads up to the line break, so the line break is still in the buffer.
use
cin.ignore(); //dont forget to use cin.ignore() as it will clear all previous cin
getline(cin, sentence, '\n'); //take the sentence upto \n i.e entered is pressed
You don't have the loops wrong. What's wrong is that you are assuming that
cin >> sentence;
does something different from what it really does.
If you want to read a line of text, then do this
getline(cin, sentnence);
Your code reads a single word only.
use cin it will end with a newline or a space
eg:
when you input hello world it will get hello
and you can try
getline
it wiil end with a newline
This is working, try this.
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
int cCount;
while(1) {
cout << "Enter a character to count the number of times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
fflush(stdin);
getline(cin, sentence, '\n');
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = count(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << " " << cCount << " " << character << " " << "character(s)" << '\n';
}
cout << "Do you wish to enter another sentence (y/n)?: \n";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
after you enter first input and enter that enter is considered as input in sentence
So, you need to flush that and after that you can scan that sentence.
Try:
cCount = count(sentence.c_str(), sentence.c_str()+sentence.length(), character);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Need help with getline()
In the following code, my getline is skipped entirely and doesn't prompt for input.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
int main ()
{
int UserTicket[8];
int WinningNums[8];
char options;
string userName;
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto " << endl;
cout << "q) Quit Program " << endl;
cout << "Please make a selection: " << endl;
cin >> options;
switch (options)
{
case 'q':
return 0;
break;
case '1':
{
cout << "Please enter your name please: " << endl;
getline(cin, userName);
cout << userName;
}
cin.get();
return 0;
}
}
The problem is here:
cin >> options;
You can only extract (>>) from cin when the user hits enter. So the user types 1 Enter and that line executes. Since options is a char, it extracts a single character (1) from cin and stores it in options. The Enter is still in the stdin buffer, since nothing has consumed it yet. When you get to the getline call, the first thing it sees in the buffer is the Enter, which marks the end of input, so getline immediately returns an empty string.
There's lots of ways to fix it; probably the easiest way that fits with the model you're using in your program is to tell cin to ignore the next character in its buffer:
cin >> options;
cin.ignore();