0

I'm trying to get multiple lines of input from a user via stdin (although eventually, I'd like to be able to specify a file). The idea is that the user specifies inputs within matching "<" and ">". I'd like them to be able to invoke the program and then type as many of these inputs as they'd like across multiple lines until they terminate the input with Control-D.

So they could do: "[this is a valid

input even thought it spans

three lines]" (using brackets instead of < so that my text doesn't disappear!)

I discovered I could use fscanf to easily process these kinds of fragment by using something like:

fscanf(fp, "<" "%999[^>]" ">", buffer);

But I'm having a lot of difficulty getting this to work across multiple lines, and I'm not entirely sure about the best way to loop through these inputs and put the strings between < into an array containing just the relevant string.

I've done a bit of research and people seem to have differing opinions on the use of fgets versus sscanf versus fscanf, and I'm not really sure about what the merits of each are as they related to my particular problem. I'm also not sure how to make a newline not terminate the input (as it currently does). Should I be checking the number of matches that fscanf returns, or should I be looking for an EOF terminator?

Currently, my code looks like this (I was using matches earlier to check the number of each input but have since removed that). Obviously this doesn't yet move anything to an array for the sake of simplicity. Additionally, fp is currently stdin, but I'd like to keep it robust enough that I could simply change that pointer to a file in case I wanted to read from a file.

char buffer[1000];

while(true){
    int matches = fscanf(fp, "{" "%999[^}]" "}", buffer);
    if (feof(fp)) break;
    printf("%s\n", buffer);
}
Alex Alifimoff
  • 1,850
  • 2
  • 17
  • 34
  • you can read http://stackoverflow.com/questions/13592875/reading-multiple-lines-of-input-with-scanf to see if it helps. – SSC Oct 01 '14 at 01:51
  • You can make use of getline() to fetch a line of input from stdin. – Gopi Oct 01 '14 at 08:15

0 Answers0