简体   繁体   中英

C Deleting the newline at the end of a string acting weird

So I have the following code:

printf("the output is: %s.\n", intCAPass);

Which prints the following:

the output is: intercapass
.

So I tried the two following options to get rid of the newline at the end of the string intCAPass :

intCAPass[strlen(intCAPass)- 1] = '\0';
strtok(intCAPass,"\n");

but both give me the following output:

.he output is: intercapass

So I'm wondering whats going on here.

More info:

OS: Linux

The variable intCAPass receive the string from a function that reads a file containing interca\\n . So, I use a buffer in which I copy the whole file and at the end I do buffer[len] = '\\0'; and at some point I thought it could cause some problems but I don't think so.

.he output is: intercapass

You have a Windows-style CRLF ( \\r\\n ) line ending in the input string. When the final newline \\n is removed, the carriage return \\r is left in the string. When printed, it moves output back to the start of the line. Thus the final dot overwrites the first letter of the output line.

These should show similar behaviour:

printf("string one: %s.\n", "blah\r\n");
printf("string two: %s.\n", "blah\r");

Check the character before the \\n at the end of the string against a \\r , and remove that one too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM