I have just started work on asmall program that sends text over net (TON) I havent quite started but when I compile this happens when I have a space in my name
Username: Knight Hawk3
LAN (1) or Net (0):
(Here it wont let me enter data)
Process returned 1 (0x1) execution time : 3.670 s
Press any key to continue.
Here is what normally (should) happen
Username: Knight
LAN (1) or Net (0):
1
Process returned 1 (0x1) execution time : 2.134 s
Press any key to continue.
Here is my source
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <iostream>
#include <string>
using namespace std;
bool firstrun = true;
int main() {
if (firstrun) {
cout << "Username: ";
string name = "";
cin >> name;
while (name == "") {
cout << "Invalid Enter a new name: ";
cin >> name;
cout << "\n";
}
}
cout << "LAN (1) or Net (0): ";
int type;
cout << "\n";
cin >> type;
while (type < 0) {
cout << "Invalid LAN (1) or Net (0): ";
cin >> type;
}
return true;
}
I am running WIN7, Using Code::Blocks
Why is this happening with a space?
std::cin reads till the first space but keeps the rest in buffer, which will be used on the following std::cins.
If you want to read till the first '\n'(hitting enter) you have to replace std::cin with
std::getline(std::cin, name);
Related
I have a while loop in c++ like
bool stopped = false;
while (!stopped) {
string input;
cin >> input;
if (input == "stop") {
stopped = true;
}
}
and it isn't stopping where it just has a blank line when I use the stop
my full code is
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
bool stopped = false;
ofstream script;
string scriptname;
getline(cin >> ws, scriptname);
script.open(scriptname);
while (!stopped) {
string input;
cin >> input;
if (input == "line") {
string lineInput;
getline(cin >> ws, lineInput);
int i = lineInput.find(',');
lineInput[i] = ':';
script << lineInput << endl;
} else if(input == "wait") {
string waitInput;
getline(cin >> ws, waitInput);
if (!(waitInput.find(',') != string::npos)) {
script << "***" << endl;
} else {
script << "***" << waitInput << endl;
}
} else if(input == "action") {
string actionInput;
getline(cin >> ws, actionInput);
int i = actionInput.find(',');
actionInput += ')';
actionInput.insert((i + 2), 1, '(');
script << actionInput << endl;
} else if(input == "stop") {
stopped = true;
}
}
script.close();
return 0;
}
I am using the input where I first enter "test" then hit enter, then after that I type "stop" and hit enter, it generates the file but after I use the stop part it just has a blank line.
it turns out that it was just because the atom package I was using to run it doesn't stop it for some reason, I tried using konsole instead of just atom and it worked
Well, since this code stops when I enter stop (I'd suggest trying it locally to confirm), there must be a problem in the code you haven't shown us.
#include <iostream>
#include <string>
int main() {
bool stopped = false;
while (!stopped) {
std::string input;
std::cin >> input;
if (input == "stop") {
stopped = true;
}
// some more code here?
}
}
I'd be guessing that the loop is stopping but that other code you have is still doing something to the output file you mentioned in one of your comments. For example, if you have some code where my // some more code here? comment is, it will execute even if you've entered stop. The actual loop won't exit until it goes back to the while bit.
Until we see the real code, there's not much else we can do.
And, now that you've added your full code, I'm pretty confident the problem doesn't lie with the code. Running that exact code on my system gives:
pax:~> g++ --std=c++17 -Wall -Wextra -Wpedantic -o prog prog.cpp && ./prog
test
stop
pax:~> wc test
0 0 0 test
It exits on stop and the resultant file contains nothing, as expected.
Now it may be an environmental problem caused by the way you're running it. I know that running stuff within Visual Studio will sometimes leave the window open for you but it at least prints something to inform you of that:
C:\Users\Pax\ConsoleApp1.exe (process 5400) exited with code 0. Press any key to close this window . . .
If you are running it from an IDE, I would run it from a proper shell (cmd.exe or a terminal) just to check if this is the case.
As an aside, I have modified your code a little so you know what it's doing at each point (with prompts rather than just a blank line with cursor):
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
bool stopped = false;
ofstream script;
string scriptname;
cout << "scriptname: ";
getline(cin >> ws, scriptname);
script.open(scriptname);
while (!stopped) {
string input;
cout << "input: ";
cin >> input;
if (input == "line") {
string lineInput;
cout << "lineInput: ";
getline(cin >> ws, lineInput);
int i = lineInput.find(',');
lineInput[i] = ':';
script << lineInput << endl;
} else if(input == "wait") {
string waitInput;
cout << "waitInput: ";
getline(cin >> ws, waitInput);
if (!(waitInput.find(',') != string::npos)) {
script << "***" << endl;
} else {
script << "***" << waitInput << endl;
}
} else if(input == "action") {
string actionInput;
cout << "actionInput: ";
getline(cin >> ws, actionInput);
int i = actionInput.find(',');
actionInput += ')';
actionInput.insert((i + 2), 1, '(');
script << actionInput << endl;
} else if(input == "stop") {
stopped = true;
}
}
script.close();
cout << "EXIT\n";
return 0;
}
That appears to work just fine with everything being written to the file. However, there is at least one small coding error (in multiple paces):
int i = lineInput.find(',');
lineInput[i] = ':';
If you enter a line with no commas, i will be set to std::npos, which is -1 (or the unsigned equivalent). If you then use that as an index in the second line above, it'll either change a character a long way past the end of the string or the character before the start of the string. Both those cases are undefined behaviour (which is why I haven't spent much time researching it).
You should probably have protection similar to the condition found in the wait case:
int i = lineInput.find(',');
if (i != std::npos) {
lineInput[i] = ':';
}
You'll also need something similar in the action case as well (for the insert call), and I'd get rid of the double-negative in wait:
// if (!(waitInput.find(',') != string::npos)) {
// Instead, you <humour> shouldn't not </humour> do it this way:
if (waitInput.find(',') == string::npos) {
script << "***" << endl;
} else {
script << "***" << waitInput << endl;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
bool exit = true;
bool wrongssn = false;
string menu;
cout << "To add a record, type add.\n";
cout << "To find someone by SSN, type find by ssn\n";
cout << "to display all records, type display all\n";
while (exit == true) {
cin >> menu;
if (menu == "add") {
cout << "ye";
}
if (menu == "find by ssn") {
cout << "Type the SSN you wish to search by";
int ssn;
cin >> ssn;
if (!cin) {
cout << "invalid choice, retry.\n";
}
}
im trying to get my second if statement to print out, but when I run the program, if I type "find by ssn", it will not print anything and keep asking me for keyboard input until I manually close out of the program.
This is because when you do cin>>menu, then menu stores find and not find by ssn because taking string input using cin stops after it encounters a whitespace. Instead use std::getline.
Syntax:
std::getline(std::cin, menu);
I have been struggling with a certain error that doesn't make sense to me. Whenever I try to compile this program, it tells me that I'm missing a semicolon when I am not.
It seems the error is linked to a specific block of code, that being the if statement that checks stock. Since I know c++ can be platform specific, I'm running debian 9 and the atom ide if that's any help.
Here is the specifc error:
error: expected primary-expression before ',' token
getline(string,line);//gets string`
and the code:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
cout << "store stocking system: \n"; // yadda yadda yadda UX
cout << "commands: \n";
cout << " help: shows available commands\n check stock: checks store stock\n enter stock: enter new stock items\n";
cout << " exit: terminates the program\n clean house: deletes all stock\n";
home: // main loop in program
string output;
output = ">> ";
cout << output;
string stock;
string item; // this whole block just defines things and gets input
int itemNumber;
string userInput;
getline(cin,userInput);
if (userInput == "exit")
{
return 0;
}
if (userInput == "enter stock")
{ // enters new stock
cout << "enter item\n>> "; //item name
cin >> item;
cout << "enter amount\n>> "; //amount of item
cin >> itemNumber;
ofstream myfile; //makes file
myfile.open("stock.txt"); //opens myfile
myfile << "\n" << item << "," << itemNumber << "\n"; //writes to file
myfile.close();// closes file
cout << "done";
goto home; //finishes and goes to main loop
}
if (userInput == "check stock") // where the problem is
{
string line;
ifstream file("stock.txt");//checks fo file
file.open("stock.txt");//opens file
getline(string,line);//gets string
file.close();//closes it
cout << line << "\n";
goto home;
}
if (userInput == ""){
goto home;
}
else
{
cout << "\033[1;31mplease use a proper command:\033[0m\n";
goto home;
}
return 0;
}
Are you missing this by any chance?
#include <string>
I believe it simply needs to be getline(file,line) rather than getline(string,line) and then you should be sorted.
string is recognized as a type name, of type std::string which you generously exposed by line using namespace std;. This particular error message is caused by fact that string isn't an expression which can be evaluated . In context of your code it should be
getline(file,line);
PS. Standard would say that you have to include <string> header to use component std::string. Your code compiles thanks to an implementation-defined feature, was imported with <iostream> in this version of header.
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.
My program takes user data as a tuple and stores it into a vector. There is no limit to how many tuples can be added and vector size changes with the adding of tuples. The program asks the user if they want to add another tuple. If no, the loop exits.
My problem is, when the program was supposed to wait for 'yes' or 'no' input, it skipped the cin and exited the loop.
I have tried searching for solutions, tried clearing the buffer but I am back to square one.
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
void print(vector<tuple<int, string, string, bool>> const & data)
{
if (data.size() != 0)
{
for (auto row : data)
{
cout << get<0>(row) << ", " << get<1>(row) << ", " << get<2>(row)
<< ", " << get<3>(row) << endl;
}
}
else
{
cout << "\nNO ENTRIES CURRENTLY!";
}
}
int main()
{
int id;
char go;
string name, filePath;
bool flag = false;
typedef tuple<int, string, string, bool> pData;
vector<pData> pList;
do
{
cout << "Enter a Pattern Call:" << endl;
cin >> id >> name >> filePath >> flag;
pList.push_back(make_tuple(id, name, filePath, flag));
cout << "Do You wish to add another: ";
cin.ignore();
cin >> go; //The control skips here and exits the loop.
} while (go == 'y' || go == 'Y');
print(pList);
return 0;
}
I have a hack which seems to work on my Linux Machine.
Add cin.clear() before cin.ignore()
Replace cin.ignore() with cin.ignore(1)
Part of your code should look as below:
cout << "Do You wish to add another: ";
cin.clear();
cin.ignore(1);
cin >> go; //The control skips here and exits the loop.
Look here:
How do I flush the cin buffer?
Using cin is not that easy or safe if user input is not exactly what we want.