C++ store string sentences from user input into a vector - c++

I am a beginner at C++ and currently learning vectors. Here is a simple code where program gets the user input and stores it in a vector then proceed to print the stored values from each element:
int main(){
vector<string> myVector;
string myInput;
int n;
cin>>n;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
for(int i = 1; i <= n;i++){
cout<<"loop count: "<<i<<endl; //added for checking the current loop
getline(cin, myInput);
cin.ignore(numeric_limits<streamsize>::max(),'\n');
myVector.push_back(myInput);
}
for(unsigned int j = 0;j < myVector.size(); j++){
cout<<myVector[j]<<endl;
}
return 0;
}
but when I run my code, during the user string input, it lets me enter two strings before finally going to the next loop. the program only prints out the first entered string for each loop though. So my questions are:
1) What is the reason behind this? Why does user need to enter two strings before going to next loop? Can someone explain to me.
2) how can this be fixed?
EDIT: Here are my sample inputs and the output:
input:
3
input loop count: 1
we are
the champions
input loop count: 2
no time
for losers
input loop count: 3
we are
the champions
output:
we are
no time
we are

The problem is the ignore call inside the loop.
The std::getline will silently eat up the trailing newline, but since you then call ignore you must enter a second line for ignore to be satisfied.
Simply remove the ignore call from the loop and it should work as you expect.

Did you try to put cin.clear(); cin.sync(); before getline function? cin and getline give you problems when you use them at the same time.

Related

How to break a loop when "enter" is pressed in C++ while taking input in an integer array

I have this loop, where arr is an integer array.
for(int i=0; i<=counter;i++)
{
cin>>arr[i];
}
I'm giving input like this
2 4 6 7
I want when enter is pressed after 7, just break this loop.
I think it can be done with something like
if(cin.get()=="\n")
But I can't understand how to implement it here in this code.
If you wanted to exit your for loop when you press the Enter Key. You would need to check the given input before putting it in your array.
And if it is equal to '\n', leave the for loop with break.
for (int i = 0; i <= counter; i++) {
// Check if user pressed the Enter Key
if(std::cin.peek() == '\n') {
// Leave the for loop
break;
}
std::cin >> arr[i];
}
To ensure that the input doesn't get cleared from cin.get() we can instead use cin.peek().

How does count become 5 here?

I am learning the use of get() and put() in c++. I have the following two doubts:
As we are in the while loop, why don't the characters get printed as soon as I enter them as there is a put right after the get?
Why does count has the value 5 instead of 4? When I hit the Enter key, I will exit the loop(at least that's what I understand). So we have count = 4 when the loop ends.
Here is the code:
#include<iostream>
using namespace std;
int main() {
int count = 0;
char ch;
cout << "Input text\n";
while(ch != '\n') {
cin.get(ch);
cout.put(ch);
count++;
}
cout << endl << count;
return 0;
}
Any kind of help is really appreciated. Please consider me a beginner in C++. Thanks.
The loop first enters cin.get() and does not continue until you enter all your 4 characters. It has to have a new line to continue. After you enter all your 4 characters, the loop continues and reads the characters one by one.
The value of count is 5 because it also gets incremented when you enter the new line. The new line is also a character. Your input is not abcd but abcd\n. And after it completes that last iteration, it checks the condition and sees that the last character is a new line and this is when it terminates.

Exiting Loop using Enter(Return Key) C++

First of all thanks for answering and helping out...
Now i was making a program to let the user enter any number... and then use the program to point out the total number of 4's in the the number entered and i have now encountered a problem..
This is my first post here so please excuse me if i make any mistakes..
The Code
int main()
{
int T,i,j,l;
char N,p[10];
cin>>T;
while(T--) //The number of times a user can enter a new number
{
cout<<"\nEnter Numbers\n";
l=0;i=0;
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!=' '); //Now here between '' something has to be present so that the loop
//terminates as soon as the enter key is pressed right now as soon
//as the spacebar is hit the loop will terminate.
cout<<"\n";
j=0;
for(i=0;i<l;i++) //using l so that the loop runs accordingly
{
if(p[i]=='4')
{
j++; //for couting the number of 4's
}
cout<<p[i]<<"\n"; //wont be needing in the final program but here cout is just
// to check the output
}
cout<<"\n THERE ARE "<<j<<" FOURS\n";
}
}
Please not that i already have a solution for my program so please DO NOT provide a different code using some different logic... i really need this very same program to work.i know that this program can be made to work using string length but here i want the loop to terminate after the enter key is pressed.
Well if you want to stop getting input when the user presses enter instead of space you need to test against '\r', '\n' or '\r\n' depending on what OS you are using. That said you really should be using standard C++ if you are going to use C++. You could easily make your code like:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int loops;
std::cout << "How many numbers to check: ";
std::cin >> loops;
std::cin.get(); // eat newline
for (int i = 0; i < loops; i++)
{
std::string numbers;
std::cout << "Enter numbers and press enter: ";
std::getline(std::cin, numbers);
auto numberOf4s = std::count(numbers.begin(), numbers.end(), '4');
std::cout << "Number of 4's entered: " << numberOf4s << std::endl;
}
return 0;
}
Live Example
You can to see check if N is equal to '\r'. So your while loop looks like
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!='\r');

how to check if inputed value is valid value in c++

I checked many links on Stack and to other site. Most of it does it what is supposed to do, but not "exactly" how I want to. Here is the problem and the best solution that i found on online.
I want to enter a number, float for example and input should be checked if is a float or not.
I'm using this snippet found online. Also to mention that i need to repeat validation each time for loop its iterated.The "n" is entered separately before this function and its in "private".It does its job perfectly, except ...If you enter "55" (number), it checks and validates. That's ok.
If you enter "dfgfd" stuff (not a number), it checks and repeats question. That's ok.
If you enter "dfgdfgdg55",it checks and repeats question. It's also ok. If you enter "55dfgfd" stuff, it checks and NOT repeats. That's NOT OK.It just discarding characters after numbers.I want to discard this also.So correct input should be JUST "55" entered.(Number 55 is just a example number entered when prompted).Also I tried this on a simpler function "model".First to enter "55", second to enter "55gdf". They been presented on screen as "55" and "55". Then i added some code afterwards to compare these numbers. They are not the same!
#include <iostream>
using namespace std;
int Provera_kucanja()
{
cout<<endl;
cout<<"Input boundary for an array"<<endl;
cin>>n;
while (cin.fail() || !(n>0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cin>>n;
}
cout<<endl;
return 0;
}
float Unos_brojeva()
{
cout<<"\n";
cout<<"Now you must enter number into array:\n "<<endl;
for (int i = 0; i < n ; i++)
{
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
float r;
cin>>r;
while (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
cin>>r;
}
unos[i]=r;
}
cout<<endl;
cout<<"Now show unsorted array members: "<<endl;
for(int i = 0; i < n; i++)
{
cout<<"This is "<<"["<<i<<"]"<<" member of array named 'unos': "<<unos[i]<<endl;
}
cout<<"\n"<<endl;
cin.get();
return 0;
}
int main(){
Provera_kucanja();
Unos_brojeva();
}
On the down side using suggested answers is that when user enters something like "ghfg" , result of this conversion is a ZERO!. So suggested answers is no-go's.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string A_number;
char* An_array=new char[A_number.length()];
cout<<"Enter value for A_number: ";
cin>>A_number;
strcpy(An_array,A_number.c_str());
float n=atof(An_array);
cout<<"Value entered is: "<<n;
cin.get();
return 0;
}
The line:
cin >> r
is going to try to read a valid float, even if there is bad trailing information after it.
You are saying the problem occurs when someone enters 55x, in this case you think it should not be considered a valid number.
There is an answer to your problem here: https://stackoverflow.com/a/19717896/312594
What you have to do is read the entire data in as a string and confirm that only characters that are possible as float input (digits, ., +, -, etc.) are in the input, and in the correct possible order. Only after you validate the input do you convert the input to float (via cin or some other mechanism).
In most cases you should accept 55x as 55 since that's probably what the user wants, but if you do want to be strict you have to perform the additional validation yourself.
p.s. - I almost hate to say this as I do not want to sound biased, but as you're learning C++ you may find it useful to write all of your code, including prompts, in English. If you later ask for help on StackOverflow, it will be easier for more people to understand what you are trying to do and therefore to help you out.
Sounds like you want to read in the input as strings (or possibly whole lines), and then you can test those strings any way you like.

cin wont work in loop

Ok so im trying to learn c++, and i was making a simulation but the cin wont work for me :(
void Simulation::initialize(){
cout<<"Choose number of players: " <<endl;
cin>> numberOfPlayer;
string name;
int accurasy;
int life;
for(int index=0; index <=numberOfPlayer;++index){
cout<<"Enter name, accurasy and life for player"<<index +1 <<": " <<endl;
cin>>name;
cin>>accurasy;
cin>>life;
Kombatant comb(name,accurasy,life);
vect->push_back(comb);
}
}
This is the code that wont work for me. Im trying to add players to the simulation. Everything works as expected until i get in to the for loop. For some reason it only works in the first looping until i get to life. Then it skips the life input and every input after that (every input in all the loops). Anyone have any ideas what the problem is ?
It's because the last newline is still in the input buffer. So when you loop the input of the name will see the newline and give you an empty input.
You have to tell the input stream to explicitly skip it:
// all your input...
// Skip over the newline in the input buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')