Fix spacing in copycat program - c++

Here is my code for a basic copycat program that just copys whatever the user types:
#include <iostream>
using namespace std;
#include <string>
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin;
}
return 0;
}
But when the user inputs more than one word i get this:
Me: more
You: than
You: Me: one
You: Me: word
You:
any and all help is appreciated! thank you!

You need to use cin.getline(usrin) instead of cin >> usrin.
cin >> usrin stops reading when it finds whitespace characters in the stream but leaves the rest of the stream for the next time cin is used.
cin.getline will read until the end of the line. However, you will need to change usrin to an array of char.
char usrln[MAX_LINE_LENGTH];
where MAX_LINE_LENGTH is a constant that is bigger than the length of the longest line you expect to see.

After each input, \n leaved behind in input buffer and read on next iteration. You need to flush your input buffer. Use
cin.ignore(MAX_INT, '\n'); //Ignores to the end of line
Add <limits.h> header.
#include <iostream>
#include <limits.h>
#include <string>
using namespace std;
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin ;//<<endl;
cin.ignore(INT_MAX, '\n');
}
return 0;
}

Related

C++ istream (cin) and problem with waiting for a ENTER key press

Please, is there a way I can wait for a single ENTER key press in all of the below cases? It works fine except when the std::getline() is used, which consumes the \n, and the ENTER needs to be pressed twice.
The code below works fine:
#include <iostream>
#include <limits>
using std::cout;
using std::cin;
using std::string;
void waitForENTERKeyPress();
int main ()
{
char c;
string s;
cout << "Enter c:"; cin >> c;
waitForENTERKeyPress();
cout << "Enter c:"; c = cin.get();
waitForENTERKeyPress();
cout << "Enter s:"; cin >> s;
waitForENTERKeyPress();
cout << "Enter s:"; std::getline(cin, s);
waitForENTERKeyPress();
return 0;
}
void waitForENTERKeyPress()
{
// Does not work with std::getline(...)
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Press an ENTER to continue...\n";
cin.get();
}
====[UPDATE]============================================
Let me rephrase what I am looking for: The way how to make the waitForENTERKeyPress() function working in both cases – with \n in the buffer, when cin operator >> or cin.get() is used and also in cases the std::getline() is used.
From what I understand it is not possible as there is not a way how to detect if the \n is still in the buffer or not.
I have tried to use cin.rdbuf()->in_avail(), but it always returns 0.

How to make string variables more than one word c++?

When I am trying to store more than one word in a string variable, it only outputs one word when I tell the program to print it. This is an example:
#include <iostream>
using namespace std;
string i;
int main() {
cout << "Input more than one word." << endl;
//in this case the user will input whats up//
cin >> i;
cout << i << endl;
//the program outputs 'whats'//
}
Instead of using cin >> i, use getline(cin, i).
The difference is that, with getline() you get all the words in a line, whereas with operator>> you get only one word at a time.
Replace that:
cin >> i;
for:
getline(cin, i);
and it will work :)

Using std::getline() to read a single line?

My goal is to prompt user to enter a message / sentence and then print it out on the screen, using getline(). The following is two different attempts I have tried out.
First Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
chat message[80];
cout << "\n what is your message today?" << endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
}
Second Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
string a = "a string";
cout << "\n what is your message today?" << endl;
while(getline(cin,a))
cout << a;
cout<<endl
}
}
For the fist attempt, the code simply print out "what is your message today?" and quit. I do not have a chance to enter any string at all. For the second attempt, it keeps asking me enter the message. Each time, when I enter something with the "\n", it would display what I entered on the screen. I use control + c to interrupt the running process to make it stop.
EDIT: To clarify and explain on my side, I extract the first attempt from a longer code, which is as the following.
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "\n *** C Strings ***\n\n"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
string a="fivelength";
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
cout << "\nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}
For the above code, it does not give me a chance to enter a message on the screen. I will put it as another question.
You are overcomplicating this, you can simply use std::string, which is the de-facto C++ string, and call the method, without using a loop.
You don't need a loop, since you are not going to repeatedly read lines, but only want to read one line, so no loop is needed.
#include <iostream>
#include <string> // not cstring, which is the C string library
using namespace std;
int main(void)
{
string message; // it can be an empty string, no need to initialize it
cout << "What is your message today?" << endl;
getline(cin, message);
cout << message;
cout<<endl;
return 0;
}
Output (Input: "Hello Stack Overflow!"):
What is your message today?
Message: Hello Stack Overflow!
PS: As #fredLarson commented, if you change chat to char in your first example, it should work. However, that code has a lot of commonalities with C.

Not waiting for std::cin.ignore()

Based on this answer, I've written the following code
#include <iostream>
#include <vector>
#include <cstddef>
#include <limits>
int main()
{
std::cout << "Enter x and y size, followed by enter: ";
std::size_t nrOfRows, nrOfCols;
std::cin >> nrOfRows >> nrOfCols;
// initialize dynamic array of arrays
std::vector<std::vector<char>> data(nrOfRows,
std::vector<char>(nrOfCols, 'O'));
// print array
for (std::size_t rowNr = 0; rowNr < nrOfRows; rowNr++)
{
std::cout << "Row " << rowNr << ": ";
for (const auto& el : data[rowNr])
std::cout << el << " ";
std::cout << std::endl;
}
std::cout << "Press enter to continue: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Compiled with VC++ 14.1 or Visual studio 2017 v15.7.4.
After the first prompt I enter e.g. "3 5" and enter. Then the program just rolls through and exits. E.g. it outputs the strings and does not wait for the final user input (enter) at std::cin.ignore().
What did I miss?
edit
For the down-voters/nay sayers. This code does work as described.
#include <iostream>
#include <limits>
int main()
{
std::cout << "Press enter to continue: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Your problem is that the extraction operation (std::cin >> nrOfRows >> nrOfCols;) will leave delimiting whitespace in the stream, unlike getline(), which will consume the delimiter. This normally isn't a problem because the >> operator will also ignore leading whitespace, but the line break left in the stream will cause std::istream::ignore() to not wait for input.
To fix this, add a call to std::istream::ignore() to discard any whitespace before you output the Press enter to continue: message.

String not turning blue and only reading up to space

Here's my actual code, it's skipping the getline(cin,phrase) completely..
maybe there's something else wrong with it, but I can't really find anything wrong.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream outFile;
string file_name;
string phrase;
int number;
cout << "What file would you like to write into? ";
cin >> file_name;
outFile.open(file_name);
if(!outFile)
{
cout << "Error, could not find file. Press enter to self destruct. " << endl;
return -1;
}
cout << "What would you like to write? ";
getline (cin, phrase);
cout << "How many times? ";
cin >> number;
while(number != 0)
{
outFile << phrase;
number = number - 1;
}
system("pause");
return 0;
}
cin would read as far as whitespace is not there in your input string. To get around that you can use
getline( cin, cookie ).
OR
char input[100];
cin.getline(input,100);
EDITED AS TO CLARIFY:-
Show me the output for this :-
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cookie;
getline ( cin, cookie );
cout << cookie;
system("pause");
return 0;
}
The >> operators read formatted input in term of "space separated items", so
aaaaa bbbb 123
are actually three distinct elements. The first two can be string, the third can be a string or whatever numeric scalar type.
If you want to consider spaces as part of the read, the proper function shold be getline