The issue is detecting '\n' when I loop through my array. It works once as shown in the comments, but it does not work after. The goal of this program is to take input from the terminal and put it into an array. The array should not contain any '\n'. Any help is appreciated, Thanks
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// 1. Function must take input and place in array whilst making sure it does not overflow
// 2. Must return null if end of stdi is reached
// 3. Must ensure that it does not contain delimeter \n
// Tests:
// a) empty string
// b) string longer than buffer
// c) what happens when you press ctrl-d
char read_line(char *buf, size_t sz) {
while(fgets(buf + strlen(buf), sz, stdin)){
if (strlen(buf) < sz) {
if(buf[strlen(buf)-1] == '\n' ){
// IT GET'S DETECTED HERE WHEN THE ENTER
// BUTTON
// IS PRESSED BUT ...
break;
}
}
}
// WHEN I LOOP THROUGH THE ARRAY IT GETS DETECTED AS SINGLE CHARS; '\'
// AND 'n' DISTINCTLY
for(int i = 0; i < strlen(buf)-1; ++i){
if(buf[i] == '\n'){
printf("present");
} else {
printf("x");
}
}
return NULL;
}
int main(int argc, char *argv[]){
char arra[20];
size_t sz = sizeof(arra);
memset(arra, 0, sz);
printf("Enter command: \n");
read_line(arra, sz);
// Print elements in array
printf("Printing out array: \n");
for(int i = 0; i < strlen(arra); ++i){
char c = arra[i];
printf("%c", c);
}
}
You appear to be entering something like the keystrokes hello\nENTER.
The entry of the two distinct characters \
and n
are exactly that, two distinct characters. That is vastly different to the single newline character which is represented in the source as \n
.
In terms of what the buffer will hold, it'll be the string "hello\\n\n"
, where \\
is the \
character, n
is an n
, and \n
is the newline.
If your intent is to detect the newline in the string, you'll need to process every character in the string. The loop:
for (int i = 0; i < strlen(buf) - 1; ++i) ...
will basically skip the last character, which is fine for ignoring trailing newline should it exist but, if you want to detect it, you'll need:
for (int i = 0; i < strlen(buf); ++i) ...