0

I wrote the following C++ program to capitalize the first letter of each word in a sentence entered by the user:

#include <iostream>
#include <string>
using namespace std;

int main() 
{
  char Intstr[255];
  char Outstr[255];
  fgets(Intstr,255,stdin);
  
  int i = 0;
  Outstr[0] = toupper(Intstr[0]);
  for (i = 1; Intstr[i]; i++)
  {
    if (Intstr[i-1]==' ')
    {
      Outstr[i]=toupper(Intstr[i]);
    }
    else
    {
      Outstr[i]=Intstr[i];
    }
  }
  cout << Outstr << endl;
  
  return 0;
}

When I entered "hello world" into the command line, the expected output is "Hello World". However, the actual output is

Hello World╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠hello world

How can I fix this code so that the output is "Hello World"?

  • 4
    Seems like it doesn't end with '\0' – Sreeraj Chundayil Jul 17 '21 at 16:58
  • 3
    You need to add the `\0` in `Outstr` since you break the loop before doing so. – Holt Jul 17 '21 at 17:00
  • 1
    Specifically, you stop the loop when you encounter the `\0`, but you never run an iteration of the loop for it. –  Jul 17 '21 at 17:02
  • 4
    Any [decent book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should tell you to use `std::string` for all your strings. And that otherwise they are really called ***null-terminated** strings*. – Some programmer dude Jul 17 '21 at 17:04
  • 1
    Does this answer your question? [What is a null-terminated string?](https://stackoverflow.com/questions/2037209/what-is-a-null-terminated-string) – Sreeraj Chundayil Jul 17 '21 at 17:24

1 Answers1

1

The Intstr[i]; condition of the for loop stops the loop before it copies the null terminator (AKA: '\0', or just 0). So, add this one line after the for loop to copy the null terminator to the output C-string too.

  } // end of for loop
  Outstr[i] = Instr[i]; // copy the null-terminator too  <== ADD THIS LINE
  cout << Outstr << endl;

Remember, raw C-strings, unlike C++ std::string class objects, must always end in a null-terminator in order to mark where they end.

Otherwise, printing or using them will print whatever it finds from the start of the string to the first null-terminator it finds, which could be well-outside your C-string. All of the stuff read and printed outside of your C-string is a result of "undefined behavior", meaning the C and C++ standards make no guarantee of what will happen or what will be printed there. Usually, you get garbage characters from whatever happened to be sitting in memory there.

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265