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.
Posts: 3
Joined: Fri Jan 03, 2014 12:38 am
Gender: None specified

Problems with C strings (char*)

Postby smprogrammer » Sat Jan 04, 2014 3:07 pm

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
COJ Administrator
Posts: 1968
Joined: Sun Nov 13, 2011 12:32 pm
Location: Universidad de las Ciencias Informáticas
Gender: None specified

Re: Problems with C strings (char*)

Postby ymondelo20 » Fri Jan 31, 2014 3:06 pm

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
"Every problem has a simple, fast and wrong solution" OJ's Main Law. ;)

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

Who is online

Users browsing this forum: No registered users and 1 guest