Reputation: 403
This is my code:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string userInput;
std::getline(std::cin, userInput);
int sum;
int result;
std::string numDigit;
bool space = true;
for (int i = 0; i < userInput.length(); i++) {
if (isdigit(userInput[i]) && space) {
numDigit += userInput[i];
space = false;
}else if(isdigit(userInput[i]) && !space) {
numDigit += userInput[i];
}else if (!isdigit(userInput[i]) && !space) {
std::stringstream(numDigit) >> result;
sum += result;
numDigit = "";
result = 0;
space = true;
}
std::cout << sum;
}
}
If i input 1 2 3 with space, it should ouput sum = 6, but instead it output many digits of number why is it like that ? (sorry I'm beginner of c++)
Upvotes: 0
Views: 113
Reputation: 381
You are using your variables sum and result without initializing them.
When you are using any compiler, you cannot assume that variables will be automatically initialized to zero. So, if you use an uninitialized variable, the behavior of your program will be undefined, it might be just nice the value you want, or it will be filled with garbage values like 80123901723012, -190283812791, etc...
int sum = 0;
int result = 0;
Declare a variable and initialize it to zero is always a good practice.
EDIT :
The problem your code have is:
1. you should only output sum
after for loop end.
2. your should check for i <= userInput.length()
instead of checking for less than only.
modified code:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string userInput;
std::getline(std::cin, userInput);
int sum = 0;
int result = 0;
std::string numDigit = "";
bool space = true;
for (int i = 0; i <= userInput.length(); i++) {
if (isdigit(userInput[i]) && space) {
numDigit += userInput[i];
space = false;
}
else if (isdigit(userInput[i]) && !space) {
numDigit += userInput[i];
}
else if (!isdigit(userInput[i]) && !space) {
std::stringstream(numDigit) >> result;
sum += result;
numDigit = "";
result = 0;
space = true;
}
}
std::cout << "sum = " << sum << std::endl;
}
Upvotes: 2