0

我只是从 C++ 开始,所以在这里我可能会犯一个愚蠢的错误。下面是我的代码以及评论中的输出。我正在使用 Xcode。

#include <iostream>
#include <string.h>

using namespace std;

 int main() {

          char myString[] = "Hello There";
          printf("%s\n", myString);

         strncpy(myString, "Over", 5); // I want this to print out "Over There"

         cout<< myString<<endl; // this prints out ONLY as "Over"

         for (int i = 0; i <11; i++){
         cout<< myString[i];
          }// I wanted to see what's going on this prints out as Over? There
          // the ? is upside down, it got added in

         cout<< endl;
         return 0;
}
4

3 回答 3

1

THE PROBLEM

  • strncpy (destination, source, max_len)

strncpy is defined to copy at most max_len characters from source to destination, including the trailing null-byte if source doesn't include a null-byte within the first max_len bytes.

In your case the trailing null-byte will be including, and with that destination will be null-terminated directly after "Over", which is why you are seeing the described behaviour.

After your call to strncpy myString will therefore compare equal to:

"Over\0There"

THE SOLUTION

The most straight-forward solution would be to not copy the trailing null-byte from "Over", which is as easy as specifying 4 instead of 5 to strncpy:

strncpy(myString, "Over", 4);
于 2014-03-24T01:55:08.087 回答
1

The documentation for strncopy is as follows:

char * strncpy ( char * destination, const char * source, size_t num );

Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

By calling strncpy(myString, "Over", 5), you are actually copying "Over\n" into myString. You are probably better off calling strncpy with the last parameter as strlen(source).

于 2014-03-24T01:57:02.067 回答
1

Try the following

#include <iostream>
#include <string.h>

using namespace std;

 int main() {

   char myString[] = "Hello There";
   printf("%s\n", myString);

   strncpy(myString, "Over", 4); // I want this to print out "Over There"
   strcpy( myString + 4, myString + 5 ); 

   cout<< myString<<endl; // this prints out ONLY as "Over"

   for (int i = 0; i <10; i++){
    cout<< myString[i];
   }// I wanted to see what's going on this prints out as Over? There
    // the ? is upside down, it got added in

   cout<< endl;

   return 0;
}
于 2014-03-24T01:57:03.197 回答