0

I want to save 2 strings in one variable (like "name surname"). On Windows this scanf works fine but when I run this code on Lubuntu the same scanf does not work. Why is that and how can I fix this?

printf("Give a Name and surname:\n");
fflush(stdin);
scanf("%[^\t\n]", Students[size].name);

Students[size].name is a struct that I made.

struct Eggrafes{
 char *name;
 int *pst;
}*Students;
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Read [Using `fflush(stdin)`](http://stackoverflow.com/questions/2979209/using-fflushstdin) to see why you should not use techniques that are valid (only) on Windows when you try to use the code on Ubuntu where the same technique is invalid. You will find workarounds. The easiest fix may be to put a space before the `%` in the format string; that will skip any leading white space (but won't clear non-white-space characters from the previous line). – Jonathan Leffler Oct 10 '16 at 06:23
  • 1
    I trust you're allocating space for the `name` before reading the value. Otherwise, you're running into another sort of undefined behaviour. – Jonathan Leffler Oct 10 '16 at 06:28
  • It didn't need to; there was a newline in the input buffer (still), and that blocked the `%[^\t\n]` conversion (because the newline matched the 'not match'), so it returned. If you'd tested the return value from `scanf()`, you'd have seen `0` returned, indicating that the conversion failed. The `scanf()` function is a fearsomely and subtly complex function — it is very easy to use in the simple cases and very hard to use right in the complex cases. I wish it wasn't taught so early in schools. – Jonathan Leffler Oct 10 '16 at 06:33
  • When i running the code(on visual base studio-lubuntu) doesnt even stop to write something on scanf and that i didnt understand. aslo this is the better way to save 2 strings in one variable that i know.Maybe you have some betters ideas? – Σωτηρης Ιωαννιδης Oct 10 '16 at 06:40
  • Did you try the space before the percent in the format string? It should do the trick for you on both Windows and Lubuntu – Jonathan Leffler Oct 10 '16 at 06:58
  • i try it now and it seems very good.Thank very much! – Σωτηρης Ιωαννιδης Oct 10 '16 at 07:06

0 Answers0