Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two words in a string from text file

Tags:

c

I'm trying to get two words in a string and I don't know how I can do it. I tried but if in a text file I have 'name Penny Marie' it gives me :name Penny. How can I get Penny Marie in s1? Thank you

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello world!\n");
    char s[50];
    char s1[20];

    FILE* fp = fopen("file.txt", "rt");
    if (fp == NULL)
        return 0;

    fscanf(fp,"%s %s",s,s1);
    {
        printf("%s\n",s);
        printf("%s",s1);
    }
    fclose(fp);
    return 0;
}
like image 517
Bon Bobita Avatar asked May 19 '26 07:05

Bon Bobita


1 Answers

Change the fscanf format, just tell it to not stop reading until new line:

fscanf(fp,"%s %[^\n]s",s,s1);

like image 138
EmilioPeJu Avatar answered May 21 '26 21:05

EmilioPeJu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!