Dont Understand Output

Started by
2 comments, last by toogreat4u 15 years, 8 months ago
Hello I am writing a program using MSVC++ Express 2008 and I am getting a strange output from it. The program is suppose to basically write a grammatically correct sentence with first letter being uppercase and the rest being lowercase with only one space in between words. I understand how to get the program to correctly place the items in the character array but when I output the darn array it adds all the garbage values at the end and outputs them. I do not have this problem with Linux OS but for some reason windows wants to print all 100 values of the array regardless of whether there empty or not. If someone could tell me why this is happening that would be great! Code: #include <iostream> #include <cstring> #include <cctype> #include <cstdlib> using namespace std; /* Write a program that reads in a sentence of up to 100 characters and outputs the sentence with spacing corrected * and with letters corrected for capitalization. * All strings of two or more blanks should be compressed to a single blank. * The sentence should start with an uppercase letter but should contain no ohter uppercase letters. * Treat a line break as if it were a blank, in sense that a line break and any other blanks are compressed to a single. * Assume the sentence ends with a period and contains no other periods. */ const int MAX_CHARS = 100; void input(char s[]); int main() { char sentence[MAX_CHARS]; input(sentence); cout << sentence << endl; return 0; } void input(char s[]) { char next; int blank_counter = 0; cout << "Enter in a sentence: \n"; cin.get(next); int index = 0; while(next != '.') { if(index < MAX_CHARS) { // guarantees that the first indexed item is uppercase if(index == 0) { s[index] = toupper(next); } else { // when a whitespace happens, just make a single one in the sentence // ignore the rest while(isspace(next)) { if(blank_counter == 0) { s[index] = ' '; index++; } cin.get(next); blank_counter++; } s[index] = tolower(next); } // resetting the blank counter for the next incident it occurs blank_counter = 0; index++; } cin.get(next); } s[index] = '.'; } Output: Enter in a sentence: hello and why are you printing these garbage values. Hello and why are you printing these garbage values.╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠hü◄Ö@·. Press any key to continue . . .
Advertisement
You need to put a zero at the very end of the array. Not a '0', but an integer zero (or '\0'). This is called a "null terminator" and is how text in C (and C++) knows where the end of the string is.
std::string takes care of preventing all the stupid bugs for you, so you can use your time to think about your program.
Thanks to both comments!

This topic is closed to new replies.

Advertisement