-1

hello i am new to visual studio code and i searched regarding how to read string with space in c

and got the following methods

https://www.geeksforgeeks.org/taking-string-input-space-c-3-different-methods/

so i used the scanset specifed in the above link in visual studio it was working fine for one program

to say specifically if only one scanf with scanset is present that too at first it works

following are the two programs where in first one scanset not reading any thing , so i checked in other program where scanset worked fine

here are two programs

1)where scanset not even reading a string and exits

#include<stdio.h>
#include<iostream>

int main(){
    char s[1000];
    int N,K,T = 0;
    int g=0;

    scanf("%d",&T);

    scanf("%d%d",&N,&K);

    scanf("%[^\n]%*c",s);
    
    for(int i=0;i<T;i++){
        for(int j=1;j<=N/2;j++){
            if(s[j]!=s[N-j+1]){
                g= g+1;
            }
    }
    if(g!=K){
        printf("Case #%d: %d",T,K-g);
    }
    
    
}

}

output

PS C:\Users\SriHarsha> cd "c:\Users\SriHarsha\" ; if ($?) { g++ kgoodness.cpp -o kgoodness } ; if ($?) { .\kgoodness }
1 
5 2
PS C:\Users\SriHarsha> 

where scanset read a string and gave output but when i used other scanf to read simple character the second scanf statement is not working

#include<stdio.h>
int main(){
    char s[1000];
    char d;
    scanf("%[^\n]%*c",s);
    for(int i=0;i<10;i++){
        printf("%c",s[i]);
    }

    scanf("%c",&d);
    printf("%c",d);

}

output

PS C:\Users\SriHarsha> cd "c:\Users\SriHarsha\" ; if ($?) { g++ scanf.cpp -o scanf } ; if ($?) { .\scanf }
sri
sri

PS C:\Users\SriHarsha> 
sweenish
  • 3,215
  • 2
  • 10
  • 19
SriHarsha
  • 21
  • 5

1 Answers1

0

In both cases where scanf appears to not work, the format specifier for reading a string is malformed..

This format specifier for this scanf call is malformed and won't actually read a string into variable s scanf("%[^\n]%*c",s);

If your intent is to read a string into s, I'd suggest changing that line to this: scanf("%s",s);

GandhiGandhi
  • 809
  • 5
  • 9
  • `scanf("%s",s);` will not work for OP's "how to read string with space". Without a width limit, it is worse than [`gets()`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – chux - Reinstate Monica Mar 29 '21 at 17:24
  • Monica its not showing any error value `PS C:\Users\SriHarsha> cd "c:\Users\SriHarsha\" ; if ($?) { g++ kgoodness.cpp -o kgoodness } ; if ($?) { .\kgoodness } 1 Value of errno: 0 5 2 Value of errno: 0 Value of errno: 0` – SriHarsha Mar 29 '21 at 17:34