The array I’m working with is:
char arr[91][12];
So I populate my array from a file using a for loop like so:
for(i = 0; fgets(arr[i], 12, inFile); i++){}
When I want print anything from that array, it’s automatically escaping to the next line.
to test that array:
for(i = 0; fgets(arr[i], 12, inFile); i++){
printf("%s", arr[i]);
}
//one
//two
//three etc.
//want it to be 'one two three etc.'
I’m trying to use strpbrk() to find \n for each string in the array and change it to \0 like this:
for(i = 0; fgets(arr[i], 12, inFile); i++){
if(strpbrk(arr[i], "\n") != NULL ){
arr[i][strpbrk(arr[i], "\n")] = '\0';
}
printf("%s", arr[i]);
}
but this gives me errors. Is there a better way to do what I’m trying to do?
It’s actually much simpler than you seem to think. If the newline is at the end (as it is when reading with
fgets) just change the last character to the string terminator:The
-1is because arrays (like strings can be considered to be) starts their indexing on zero and goes tolength - 1.To make sure you really have a newline, you can use e.g.
strpbrklike you do (but of course not in the way you do it as explained in other answers). But I think it would be a better idea to usestrrchr. First because it’s simpler (only searching for character not string), second because it starts searching from the end:Or the fastest way of all: