Which command lets me to cout my new random numbers by presing enter? I tried to write system("pause") but then comes line "press any key to continue" which I dont like. Is there any possibility to just press enter button and see numbers one after one?
Here's the program code:
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <ctime>
int main()
{
int i, k;
srand(time(0));
for (i = 0; i < 20; i++)
{
cout << (rand() % 8) << endl;
}
}
#include <limits>
// ...
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
The advantage over reading a single character is that this will make sure that no stray characters are left over into the buffer.
Here is a slightly more modern C++ take on it:
#include <iostream>
#include <ctime>
#include <random>
int main()
{
std::mt19937 rng(std::time(0));
std::uniform_int_distribution<int> gen(0,7);
for (int i=0;i<20;i++)
{
std::cout << gen(rng);
std::string line;
std::getline(std::cin, line);
};
}
You can simply use getchar() which will read one keypress and then continue. If you want to specifically break on the enter key, use something like while (getchar() != "\n");
add cin >> SomeVariableThatCouldAcceptAnythingInCaseYouPressSomethingElseBeforeTheEnterKey either before or after the cout, whichever you like.
Just read a string, right?
#include <string>
....
for (i=0;i<20;i++)
{
std::string str;
cin >> str; // this should pause until the user presses enter
cout << (rand()%8) << endl;
};
What about a simple cin.get()? No need for any temporary variable nor any C functions.
Related
In my program it should be an option to ask a user for input, and then save input string into the file. My problem is, - when I put cin in any of it forms, inside Switch, program will stuck circling indefinitely, right after i press enter after finish typing new text. What could cause the problem?
#include <iostream>
#include <fstream>
#include <iterator>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include <chrono>
#include <random>
#include <vector>
using namespace std;
void changePlainText()
{
ofstream nFile("plaintext.txt");
string newText;
cout << "Enter new plain text" << endl;
getline(cin, newText);
nFile << newText;
nFile.close();
}
int main()
{
int uInput = 0;
do
{
printf("2.Change content of the plain text file: \n");
cin >> uInput;
switch (uInput)
{
case 1:
break;
case 2:
changePlainText();
break;
}
} while (uInput != 5);
cout << "Closing program" << endl;
system("pause");
}
After I type something in console and press enter, the program enters never ending circle. It still stuck even if I just write simple cin >> i, in switch case.
Take a look at this question. I debugged your code and I experienced that exact behavior. The accepted answer explains quite well what's happening and also provides a solution.
I tried with boost, I changed
cin >> uInput;
to
string inputString; // so you know what inputString is
getline(cin, inputString);
uInput = boost::lexical_cast<int>(line);
and it's working fine now.
I am working on a project where I have to parse data from user input.
#include <iostream> // for cin and cout
#include <iomanip> // for setw()
#include <cctype> // for toupper()
using namespace std;
int main(){
string playerInput;
cin >> playerInput;
//Player would input strings like C13,C 6, I1, Z 16, etc...
}
return 0;
I've tried something like this, which kinda works but only if the letter proceeds the number in the string.
int myNr = std::stoi(playerInput);
What my end goal is to grab the letter and number from the string, and place them in a char variable and a integer variable respectively. I am stuck on how to proceed from here and could use some help, thanks!
This is the simplest and the shortest way to achieve that (it also ignores spaces and tabs):
int main() {
char ch;
int n;
cin >> ch >> n;
cout << "ch = " << ch << ", n = " << n << endl;
}
I think that other answers are a bit overcomplicated.
You could do like what you had:
char letter = playerInput.front();
playerInput.erase(0);
int number = std::stoi(playerInput);
Of course, that doesn't allow for spaces. Removing spaces can be quite tedious, but it could be done like:
playerInput.erase(
std::remove_if(
begin(playerInput), end(playerInput),
[](uint8_t ch) { return std::isspace(ch); }),
end(playerInput));
Full Demo
Live On Coliru
#include <cctype> // for toupper()
#include <iomanip> // for setw()
#include <iostream> // for cin and cout
#include <algorithm> // for remove_if
static bool ignorable(uint8_t ch) {
return std::isspace(ch)
|| std::ispunct(ch);
}
int main() {
std::string playerInput;
while (getline(std::cin, playerInput)) {
playerInput.erase(
std::remove_if(
begin(playerInput), end(playerInput),
ignorable),
end(playerInput));
if (playerInput.empty())
continue;
char letter = playerInput.front();
playerInput.erase(begin(playerInput));
int number = std::stoi(playerInput);
std::cout << "Got: " << letter << " with " << number << "\n";
}
}
Prints
Got: C with 13
Got: C with 6
Got: I with 1
Got: Z with 16
You have the right idea in using std::stoi. My code expands your approach:
string playerInput;
getline(cin, playerInput);
char c1 = playerInput[0];
int num = stoi(playerInput.substr(1));
The above code receives an input string, then takes out the first character and uses std::stoi on the rest of the string.
Note that I use std::getline to account for the possibility of there being spaces in the input. If you are doing this repeatedly, you will need to add cin.ignore() after each getline() statement. See this link for more info.
std::cin stops reading input when it encounters a space. You can use std::getline() if your input has spaces. To parse your string, you should check out std::stringstream. It allows you to read from a string as if it were a stream like std::cin.
#include <iostream> // for cin and cout
#include <iomanip> // for setw()
#include <cctype> // for toupper()
#include <sstream>
int main(){
std::string playerInput;
int i;
char c;
std::getline(std::cin, playerInput); // Remove trailing newline
std::getline(std::cin, playerInput);
//Player would input strings like C13,C 6, I1, Z 16, etc...
//String Stream
std::stringstream playerInputStream(playerInput);
//Read as if you were reading through cin
playerInputStream >> c; //
playerInputStream >> i;
}
return 0;
I was trying to take user input in a vector in c++, as vector is a dynamic data structure i wanted it to take input as long as user wants and when the user hit enter key it should stop taking the input (just as a string) only difference i want to do it in an integer vector, but i am unable to do so let me know if it is possible or not to take user input in a vector like the way i described.
I have searched the web for various ways but still my code isn't running the way i want, I have tried breaking the loop of input by using EOF symbols but it is not stopping the loop of input.
I have tried using cin.ignore() function but it also takes spacebar in count
i only want to stop input when enter key is pressed.
below is the most recent code i made:
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> v;
char c;
for(int i=0;;i++){
cin>>c;
if(c=='\n'){
break;
}
int x = c - '0';// typecasting char into integer.
v.push_back(x);
}
cout<<v.size()<<endl;// just to check if it is done taking input and what is the size of vector now.
}
You can use std::getline() to get the entire line and then std::istreamstream to get the integers into a vector:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
int main() {
std::string input;
std::getline( std::cin, input );
std::istringstream is( input );
std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );
std::cout << v.size() << "\n";
return 0;
}
Read the entire line as string and build each number. Something like that:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string s; getline(cin, s);
int num = 0;
vector<int> v;
for(int i = 0; i < s.size(); ++i)
if(s[i] == ' ')
v.push_back(num), num = 0;
else
num = num*10 + (s[i]-'0');
v.push_back(num);
cout << v.size() << endl;
return 0;
}
You just have to input Vector elements as a single string and use Stringstream function to assign elements in increasing order of vector's indices respectively.
Here's the code :
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
string buffer;
int data;
getline(cin,buffer);
istringstream iss(buffer);
while(iss>>data){
v.push_back(data);
}
cout<<v.size()<<" ";
cout<<"Vector Elements"<<endl;
for(int k=0;k<v.size();k++){
cout<<v[k]<<" ";
}
return 0;
}
When you read from std::cin, it will accept an entire line from the console. Your cin>>c will retrieve the first character of the line and put that character into the variable c.
This means your if(c=='\n') is pretty much pointless since the line will be consumed and you won't see an explicit '\n' as the first character...EVER.
c - '0' will convert a single ASCII character that is a digit (i.e. 0123456789) to a number you can use, but that is NOT typecasting a char into an integer. That's converting an ASCII character that happens to be a number into a numeric value. A type cast is when you change the TYPE of a value to another TYPE.
I think you want to do something like the following...
#include <iostream>
#include <vector>
#include <stdio.h>
#include <conio.h>
int main( int cArguments, const char** apszArguments ) {
std::vector<char> vchars;
char c;
do {
c = getche();
vchars.push_back( c );
} while( c != '\n' );
std::cout << vchars.size() << " characters received" << std::endl;
return 0;
}
Note that on macOS and some Linux variants, getch/getche are not defined and you'll need to use termios or ncurses functions instead.
This is definitely NOT the current syntax but just so you'd get the idea :)
#include <stdio.h>
void getWord()
{
while((c=getchar())!='\n')
{
myString.=c;
}
return myString;
}
int main(void)
{
var c=getWord();
print_f("\nCLast Word:",c);
return 0;
}
Bare in mind that I do not what to break the current line and I'm expecting to get the user input and stay on the same line even after enter key is being pressed.
Use std::getline. The function reads one line from an input stream and save it into a string.
#include <iostream>
#include <string>
int main() {
std::string input;
std::getline(std::cin, input); // get input until enter key is pressed
std::cout << input << std::endl; // print the string
return 0;
}
or you can omit std:: by "using namespace std;"
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
getline(cin, input); // get input until enter key is pressed
cout << input << endl; // print the string
return 0;
}
I'm trying to open a file and read it word by word. I can't figure out where my issue is as it seems to break down after opening the file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
There are two problems here:
You opened inputFile but then attempt to read from std::cin
"while (!inputFile.eof())" is always the wrong thing to do.
Well, there's also a third problem here:
Using a debugger would've immediately identified both problems. As an example, I loaded the compiled code in a debugger and stepped through it. The issues were readily apparent.
#Sam has all the things you did wrong.
But an alternative to using a loop is just to use iterators to build the array.
std::ifstream file(path);
std::vector<std::string> words(std::istream_iterator<std::string>(file),
std::istream_iterator<std::string>());
To print it out you can use copy.
std::copy(std::begin(words), std::end(words),
std::ostream_iterator(std::cout, "\n"));
Currently this will break words using white space as the separator between words. This means punctuation etc will be included with words. Look here on how to get the streams to treat punctuation as space: How to tokenzie (words) classifying punctuation as space
Thanks to everyone for the help. Here is the final code (for anyone who ends up Googling this in the future)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (inputFile >> test)
{
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}