Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to take one line of input separated by spaces and assign it to four variables.
I read that you're meant to be able to do:
#include <iostream>
#include <string>
int main()
{
int i, n1, n2;
std::string s;
std::cin >> i >> s >> n1 >> n2;
}
For input: 12345 string 4 5 the result would be i = 12345, s = string, n1 = 4, n2 = 5.
But I have to press enter for each variable. I need one line to assign to the four variables.
This code works already. Compile and run it, and then when the program waits for input just type in:
"12345 string 4 5", enter and you're done.
From this online CPP tutorial:
Extractions on cin can also be chained to request more than one datum in a single statement:
cin >> a >> b;
This is equivalent to:
1 cin >> a;
2 cin >> b;
In both cases, the user is expected to introduce two values, one for variable a, and another for variable b. Any kind of space is used to separate two consecutive input operations; this may either be a space, a tab, or a new-line character.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Here in this code, when I'm entering inputs one by one, I'm getting correct output as expected(correct size of string using std::string.size()), But when I'm entering three or four inputs together(or entering input in bulk) the output (size of string) gets incremented by 2.
Ps: Look once at attached output snippets.
#include <iostream>
int main()
{
int count;
std::cin >> count;
std::cin.ignore();
while (count--)
{
std::string s;
std::getline(std::cin, s);
std::cout << s.size() << '\n';
}
return (0);
}
Edit: I have printed all inputted string and found that at the end, the extra characters are two blank-spaces, as you can see below, (though I tried so far, but still don't know the reason):
5
</h1>
</h1> 7
Clearly_Invalid
Clearly_Invalid 17
</singlabharat>
</singlabharat> 17
</5>
</5> 6
<//aA>
std::cin.ignore(); ignores characters to the EOF. When you enter one line, EOF is met. When you enter several lines, EOF is not met, but \n is met. Thus the next getline after the input 5 returns the empty string, the length is 0.
When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with getline will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include:
An explicit extraneous initial call to getline
Removing consecutive whitespace with std::cin >> std::ws
Ignoring all leftover characters on the line of input with cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n');
The other line lengths are increased perhaps by the pasting the text containing \r\n that are not processed by the MS specific text file input conversions in the middle.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have the code below, so basically my problem is: when someone input a character like 'a', it will pop a message that requires a re-input
I tried using the ASCII:
if (a >= 97 && a <= 122) but it still didn't work
double a;
cin >> a;
if (a >= 'a' && a <= 'z')
{
cout << "Wrong input, please re-input a: " << endl;
cin >> a;
}
cout << a;
I expect it to pop the message to re-input but the actual output is always 0 no matter what character I input
The state of a stream can be checked by using it directly in a condition. If all is okay it "returns" true, otherwise "false". So you can do e.g.
if (!(cin >> a))
{
// Invalid input, or other error
}
On invalid input you need to clear the state.
Note that if the input is invalid then the input will not be read, and the next time you attempt to read you will read the exact same input that failed the first time. One way to solve it is to ignore the rest of the line. Another is to read a whole line into a string that you then put into an input string stream for the parsing of the input.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've been playing around with C++ (just starting out), and I'm trying to make a program that needs a function to count the lines in C++. However, I've encountered weird behavior where normal assignment doesn't work, but assignment through address of, and then immediate dereference does. Like this:
int countLinesInFile(string fileName){
char c[32];
int numLines = 0;
ifstream file(fileName);
while(file >> c){
numLines += 1;
cout << "Lines: " << numLines << endl;
}
return numLines;
}
Which results in:
Lines: 1
Lines: 1
Lines: 1
Lines: 1
Lines: 1
Lines: 1
However, when I change numLines += 1 to *(&numLines) += 1 it magically works:
Lines: 1
Lines: 2
Lines: 3
Lines: 4
Lines: 5
Lines: 6
For a little background, the file I'm reading is a 6 line file where each line is a 32 bit binary string (equal to zero). When I print out c (with cout << c) it prints out seemingly correctly. Also, I am aware that this may not be the optimal or correct way of doing read lines from a file, but unless this simply can not possibly work, I am more interested in the underlying mechanics of why this behavior is happening, and what I am doing wrong.
'\0' character binary value is 00000000. I guess that numLines is just after your array c in memory and is always erased with zeros, before being incremented by 1. So it always displays as 1.
When you compile the second version, the memory must be organized another way (only the compiler knows, and you if you debug at very low level), which does not impact numLines value.
Well, here's the answer. As StoryTeller said, the array must be 33 characters long in order to capture the terminating character and prevent the unusual behavior.
P.S. Thank you for all the helpful comments, and I agree that getline is probably a better alternative. If anyone has any insight as to how exactly this overflow might cause this weird behavior that would be very welcome.
Use class std::string with the API std::getline where you can read a whole line at each read and increment at each read the counter variable:
std::string sLine;
std::ifstream in("main.cpp");
int nLines = 0;
while(std::getline(in, sLine))
++nLines;
std::cout << nLines << endl;
in.close();
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My first stackoverflow post!
After entering a value for age into a declared and initialized int,
something weird happens and the value explodes. I test my code and could not see why it happens. After rechecking I can see that it is the last peice of code that did something to my int value.
I ask the stackoverflow gods "Why".
My code here:
int main()
{
cout << "Please enter your name and age\n\n";
string first_name;
int age(0);
cout << age << "\n\n"; // for testing why i get a huge number for age
cin>> first_name >> age;
cout << age << "\n\n"; // for testing why i get a huge number for age
cout << "Hello, " << first_name << " age " << age << '`\n';
keep_window_open(); // window must be closed manually
return 0;
}
This seems to be the offending bit:
'`\n';
This is the output I would get:
Please enter your name and age
0
et
23
23
Hello, et age 2324586
'`\n'
That's actually two characters, not only the newline feed. Plus you use single quotation marks, these are only used for single characters since char literals are of type const char.
The standard says:
The value of an integer character constant containing more than one
character (e.g., 'ab'), or containing a character or escape sequence
that does not map to a single-byte execution character, is
implementation-defined.
And thus the numbers after 23 : 24586 is the implementation-defined part that's causing weird output here. Use double quotes or '\n'.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a file that consists of data points, and numbers associated with those data points. For example, the file looks something like:
(1,2) 45
(3,4) 12
(23,9) 6 90
(3,5) 4 8
For each data point, I want to set variables "int num1" and "int num2." As you can see, sometimes I have to read an extra number attached to my data point. When there is no extra number, I set num1 and num2 to the value given. I have no problem getting the x and y from the coordinate, but I'm not sure how to check to make sure I'm getting both numbers. I feel like I have to use getline(), but I'm not sure where to go from there. The file is saved as "ins."
char parentheses1, parentheses2, comma;
int x, y, num1, num2;
ins >> parentheses1 >> x >> comma >> y >> parentheses2;
ins >> num1 >> num2;
Take Option 2 from this answer as a basis for your code.
Read from the stringstream into x and y
iss >> parentheses1 >> x >> comma >> y >> parentheses2;
and then gather numbers until there are none left on the line
std::vector<int> numbers; // dynamic array of numbers
int temp;
while (iss >> temp) // exits as soon as you can't read an int from the stream
{
numbers.push_back(temp); // store in vector
}
You can simplify the above a bit if there are never more than, say, 2 numbers.