0

Lets say i am given input

{ [1, 1], [2,10] , [-10, 20] }

I have to retrive number and check if the input is correct ( if "," isnt missing or if { and } are at the start/end )

In c, i could just use

scanf(" %c%d, %d%c",&zatvorka,&jedna,&dva,&zatvorka_dva);

In a while loop to scan the input , but how could i do it in c++? As far as i know , to cin is used to retrive data but it has no pattern like scanf() which would make it hard to retrieve data in such pattern and check if it is correct. How could i scan input like that ( for example) in c++?

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • the standard C I/O libraries are available in C++ as well http://stackoverflow.com/questions/1042110/using-scanf-in-c-programs-is-faster-than-using-cin – gokul_uf Feb 22 '16 at 08:29
  • im not sure if we will be allowed to use C I/O libraries... is scanf behavior possible with cin? –  Feb 22 '16 at 08:32
  • In that case, take the input as a string and call `stoi` to extract the relevant info – gokul_uf Feb 22 '16 at 08:35
  • 1
    What's wrong with `cin >> brace1 >> num1 >> comma >> num2 >> brace2`? – n. m. could be an AI Feb 22 '16 at 08:35
  • If your latest lessons are about parsing, see this: http://stackoverflow.com/a/35339635/1983409. – zdf Feb 22 '16 at 08:46
  • char curly_one; char zatvorka_one; int number; char comma; int number_two; char zatvorka_two; cin >> curly_one; while(cin >> zatvorka_one >> number >> comma >> number_two >> zatvorka_two){ cout << zatvorka_one << number << comma << number_two << zatvorka_two << endl; } return 0; i tried it @n.m. and with input i wrote it only printed [1,1] –  Feb 22 '16 at 10:30
  • There are commas between the pairs. – n. m. could be an AI Feb 22 '16 at 10:33
  • oh . it worked now , but how could idetect wrong input? If nothing was scanned ( for example last bracket is missing) or wrong input ( character instead of number / double instead if int) ? I tried to set cin.fail() condition right in the while loop but even inputing wrong input didnt invoke it. –  Feb 22 '16 at 20:14
  • @J.dd Could you accept my answer if it helped? – gokul_uf Feb 23 '16 at 03:56

1 Answers1

1

The scanf function is available in C++ as well. You need to include the cstdio header file to access it.

More info:

http://www.cplusplus.com/reference/cstdio/scanf/

http://en.cppreference.com/w/cpp/io/c/fscanf

gokul_uf
  • 740
  • 1
  • 8
  • 21
  • I would say it is OK to use e.g. snprintf in C++ , but do not mix printf/scanf with iostreams in the same program. E.g. performance will suffer. – Erik Alapää Feb 22 '16 at 10:28