简体   繁体   中英

C++ reading in strings and characters

Hi everyone I am working on a project for my CS class and I can't figure out how to read in part of my data file.

63f7hj-9 22spaces L Is this correct

My data file consists of this line of data and I have to figure out how to read in portions of it. I have to read in the 63 and save it as an integer and I do not need the f7hj-9. I also need to read in the 22spaces and save it as a string and the L as a character.

The phrase "Is this correct" needs to go into the console.

So my question is, how do I read in just the 63 and discard the rest of it? Save the phrase "22 spaces" as a string. L as a character And the phrase "Is this correct" as a string.

I am new to c++ and I have gotten parts of this project to work but I'm stuck on this part.

Thank you for the help.

Reading input from file and splitting the line

63f7hj-9                      L Is this correct

into integer as 63, ignoring 7hj-9 and then reading the 22 spaces in space1 string and then reading character L as a character and the rest of the string " Is this correct" inside the string str2.
This is an example of how you can use fscanf(or scanf) to achieve this.

  • %d will read the integer as it is the format specifier for integer

  • Next we need to ignore the "f7hj-9" from the file so just writing it as it is will do the job

  • Next we need to read 22 spaces so %22c will read 22 characters irrespective of whether the character is a newline or space(here 22 spaces)

  • Next we need to read a character so %c will store it in char c
  • Now another %*c will ignore the one whitespace after L
  • using %[^\\n]s will read the rest of the string until newline


Integer = 63
Spaces =                       End
Character = L
String = Is this correct


Input:

 63f7hj-9 L Is this correct 

Output:

 Integer = 63 Spaces = End Character = L String = Is this correct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM