c - Copying char array into another without copying newline -



c - Copying char array into another without copying newline -

i'm using fgets read string in char array, , want move pointer on 5 indices , re-create rest of array separate array, don't want re-create newline character; i've got this:

char str1[45], str2[50]; fgets(str2, 50, stdin); *str2 += 5; sprintf(str1, "%[^\n]s", str2);

but when seek compile, error says:

unknown conversion type character â[â in format [-wformat]

i'm pretty sure i've used "%[^\n]s" before scanf, , worked fine, suggestions?

the pattern %[^n]s valid format scanf not valid format specifier printf (or sprintf).

additionally, *str2 += 5 not skip first 5 characters (as appears intention) instead adds 5 byte stored in first element of str2. str2 = str2 + 5 not compile since str2 array. assign result temporary or pass straight sprintf.

here improve way of doing asking:

size_t len; char *str1 = null, str2[50]; fgets(str2, 50, stdin); len = strlen(str2); if (len > 5) { if (str2[len-1] == '\n') { str2[len-1] == '\0'; // remove newline len--; } str1 = str2 + 5; len -= 5; } if (str1 != null) { // stuff }

c arrays printf fgets

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -