Sign in to follow this  

Dont Understand Output

Recommended Posts

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 . . .

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this