Problems with C strings (char*)

Discussion on C, C++ and C++11 at the COJ. This is the place to clear your doubts about these languages, and to share with the community the new things you learn about them.
Post Reply
smprogrammer
Gender: None specified

Problems with C strings (char*)

Post by smprogrammer » 4 years ago

Hello everyone! :D

I've just noted something... There are a handful of problems regarding the use of strings. In most of them I plan a solution in C, which uses null-terminated char arrays as strings.

As I'm aware the use of scanf and gets is not recommended, I always use fgets with strchr together, in order to address the ENTER-in-the-string problem.

What I basically do, is the following:

Code: Select all

/* I'll read 50 characters, plus the ENTER, plus the '\0' */
char string[52] = {0};
fgets(string, 52, stdin);
/* "Empty" the input buffer */
setbuf(stdin, NULL);
/* Once I get the string, I get rid of the ENTER */
char *enter = strchr(string, '\n');
if (enter != NULL) *enter = '\0';
When I test with the given input, I get results according to the output. But when I submit it, the OJ throws WA at the first test (usually) :?

Then, I rewrite the program in C++. As I know there's the string library, I use it with iostream, so I write this equivalent. Note that I don't modify the essential algorithm, just the I/O, because I know I can use array notation in C++ strings:

Code: Select all

/* The same as above */
string str;
cin >> str;
Having the "conversion" complete, I send the problem to the OJ, and all of a sudden, it throws AC!!! :?

Am I doing something wrong when I deal with C strings?
Any help is appreciated :D



User avatar
ymondelo20
Posts: 1968
Joined: 6 years ago
Location: Universidad de las Ciencias Informáticas
Gender: None specified
Contact:

Re: Problems with C strings (char*)

Post by ymondelo20 » 4 years ago

Ummm.
Perhaps is specific to the datasets of the problem you are testing.
But you should take into account the differences between files in Windows and GNU/Linux.
Specifically the terminations of each line, wich is different for Windows (\n\r), GNU/Linux (\n) and MacOS (\r).
We use GNU/Linux :D
Regards
"Every problem has a simple, fast and wrong solution" OJ's Main Law. ;)

Post Reply

Return to “C/C++/C++11”