This question already has answers here:
How to handle wrong data type input
(4 answers)
Closed 2 years ago.
I'm sorry if this question is stupid, but it's been kind of bugging me. I have written a program that is supposed to accept user input 5 times and then print out the result each time (i am using a while loop.) Here is the code I wrote:
#include <iostream>
int main()
{
int x = 1;
int number;
while (x <= 5)
{
std::cin >> number;
std::cout << number << std::endl;
x++;
}
return 0;
}
However, after compiling and running (i'm using clang) the program only lets me insert user input once and then it just prints a bunch of 0's:
jakdfjaksdfjk
0
0
0
0
0
I am really confused why this behavior happens. Shouldn't you be able to pass in user input 5 times? Why does this behavior happen? Help would really be appreciated.
You are trying to read an integer and "jakdfjaksdfjk" would be a string, that's why that happens. Type something like 1 4 8 35 42 and it'll work as you expect
You should consider checking the validation of std::cin:
#include <iostream>
int main(void) {
int x = 1;
int number;
while (x++ <= 5) {
std::cin >> number;
// If the input isn't an integer, the breaks the loop and quit
if (!std::cin.good()) {
std::cout << "Numbers only please.\n";
break;
}
// Otherwise, simply print...
std::cout << number << std::endl;
}
return 0;
}
Related
Before, when I was writing C++, I often used getch() for validation. However, now I am turning into competitive programming, I cannot use getch(); I had to use cin or getline. Thus, today, I replicated an instance of splitting a string using stringstream:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string line;
getline(cin, line);
cout << line << endl;
stringstream reader;
reader.clear();
reader.str(line);
vector<long long int> list;
while (true) {
reader.clear();
if (reader.str().size() == 0) {
break;
}
long long int value;
reader >> value;
list.push_back(value);
}
}
Then, I ran the program, typed 1 2 3 4 5 6 7 8 9 and pressed enter. The program successfully displayed line, 1 2 3 4 5 6 7 8 9, but the program just didn't terminate. It never approached the end of the main() function. I tried to print reader.str(), but it just print 1 2 3 4 5 6 7 8 9 continually. I was confused. Why reader >> value didn't run and did not read any value? Why was the program running an infinite loop? How can I fix the issue? I appreciate any solution.
The reading operator >> does not change the underlying string. It uses an inner position of a next char to read.
int main() {
int n;
std::istringstream in; // could also use in("1 2")
in.str("1 2");
in >> n;
std::cout << "after reading the first int from \"1 2\", the int is "
<< n << ", str() = \"" << in.str() << "\"\n";
}
Outputs
after reading the first int from "1 2", the int is 1, str() = "1 2"
The loop may be terminated by replacing reader >> value; with
if (!(reader >> value))
break;
... but the program just didn't terminate.
This means that ...
while (true)
true is never false, or ...
reader.str().size() == 0
is never true.
true, in fact, is never false, and you never change the size of the reader's string object. Why would you expect this loop to break?
Please edit your question to make it more clear what you are trying to accomplish.
I'm trying to write a code that will take a number that the user inputted and create an inverted triangle like:
8 6 4 2 0 on the first line,
6 4 2 0 on the second line,
4 2 0 on the third line,
2 0 on the fourth line,
0 on the last line.
My nested for loops worked in a previous code that was in the main not in a function, but I decided I wanted to create a function that when called would run through the loops. However, something in my code isn't right since now I don't get an inverted triangle. I just get 0 and I think that's because my return is 0. I'm not sure if I'm writing my function incorrectly or if it's something else.
Please help. Thank you
#include <iostream>
using namespace std;
int row(int num)
{
int number;
int decreasedNumber;
for(int i = number; i >= 0; i -= 2)
{
decreasedNumber = i;
for(int j = decreasedNumber; decreasedNumber >= 0; decreasedNumber -=2)
{
cout << decreasedNumber << " ";
}
cout << endl;
}
return 0;
}
int main()
{
int number;
//Prompting the user to enter a number and collect that input
cout << "Enter a number: " << endl;
cin >> number;
cout << row(number);
return 0;
}
You are accepting num as a parameter to row, but never using it. Also, you are using number, but never initializing it. Instead, it seems you want number to be the parameter to the function, instead of a local variable.
Here's a demo.
Also, the variable j is never used in the loop, so you should just remove it.
Also, please don't use using namespace std;, it's a bad habit that you should avoid.
You are using number as the initial value of i.
number is uninitialized and its value is indeterminate.
Instead of number, you should use the argument num as the initial value of i.
This question already has answers here:
Why do some experienced programmers write comparisons with the value before the variable? [duplicate]
(12 answers)
Closed 2 years ago.
Out of the two versions (below) of condition check which version is better? and Why?
Version 1:
#include<iostream>
using namespace std;
int main()
{
int x;
cin >> x;
if (x == 1) // version 1
{ cout << "Hello world!" << endl;
}
return 0 ;
}
Version 2:
#include<iostream>
using namespace std;
int main()
{
int x;
cin >> x;
if (1 == x) // version 2
{ cout << "Hello world!" << endl;
}
return 0 ;
}
These are the same, the only advantage I can see relates do error detection.
Lets say you mistakenly write 1 = x, you will have a compilation error.
If you write x = 1 then the condition will evaluate to true, x will be assigned the value 1, the program will compile fine but it will not have the expected ouptput and it might be hard to detect this kind of error, though you have compiler warnings that you can turn on for this kind of situation.
This question already has answers here:
cin >> fails with bigger numbers but works with smaller ones?
(4 answers)
Closed 5 years ago.
I have recently made a program in C++ that counts a sum of digits in an input number (code below). The program works this way. A user is asked to input a natural number x. Then the program is put into a while loop which is meant to proceed until the x reaches 0. The y is a simple equation which determines the last digit of a number (i.e. x=123, y=3). D_sum is the sum of digits in x (i.e. x=123, d_sum=3).
The x=(x-y)/10 is used to help to calculate next digit (i.e. x=(123-3)/10=120/10=12). The program works fine until you input a number with more than 10 digits (screen below).
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x,y;
int d_sum = 0;
cout << "x= ";
cin >> x;
while(x > 0)
{
y=x % 10;
d_sum++;
x = (x - y) / 10;
}
cout << d_sum << endl;
system("pause");
return 0;
}
Screen:
Take a look at http://en.cppreference.com/w/cpp/language/types
, looks like on your platform int is 32 bits. e.g. if int is 32 bit, maximum number it may be able to store would 2^31 = 2147483648.
This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 3 years ago.
I'm learning C++ and writing little programs as I go along. The following is one such program:
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.
What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)
Basically your cin stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
cin >> n will return a reference to cin, which you can test for "good-ness" in a conditional. So basically the the "while(std::cin >> n)" is saying "while i could still read from standard input successfully, do the following"
EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n
EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}
Yes, Evan Teran pointed out most things already. One thing i want to add (since i cannot comment his comment yet :)) is that you must put the call to istream::clear before the call to istream::ignore. The reason is that istream::ignore likewise will just refuse to do anything if the stream is still in the fail state.
Given that you are on a 32 bit machine, 10000000000 is too big a number to be represented by an int. Also converting an int to a char will only give you from 0..255 or -128..127 depending on the compiler.
One problem here is that a char has a size of one byte, and thus can only hold a number between -127 and 128. An int on the other hand, is typically 4 bytes, and can take on much larger values. Second problem is that you are inputting a value that is too large even for an int.