简体   繁体   English

C++ 读取字符串和字符

[英]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.大家好,我正在为我的 CS 课程做一个项目,但我不知道如何读取我的部分数据文件。

63f7hj-9 22spaces L Is this correct 63f7hj-9 22spaces L 这是否正确

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.我必须读入 63 并将其保存为整数,我不需要 f7hj-9。 I also need to read in the 22spaces and save it as a string and the L as a character.我还需要读入 22 个空格并将其保存为字符串,将 L 保存为字符。

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?所以我的问题是,我如何只读取 63 并丢弃其余部分? Save the phrase "22 spaces" as a string.将短语“22 个空格”保存为字符串。 L as a character And the phrase "Is this correct" as a string. L 作为一个字符 而短语“这是正确的”作为一个字符串。

I am new to c++ and I have gotten parts of this project to work but I'm stuck on this part.我是 C++ 的新手,我已经让这个项目的一部分工作了,但我被困在这部分上。

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. 将整数转换为 63,忽略 7hj-9,然后读取 space1 字符串中的 22 个空格,然后读取字符 L 作为字符,字符串 str2 中的其余字符串“这是正确的”。
This is an example of how you can use fscanf(or scanf) to achieve this. 这是一个如何使用 fscanf(或 scanf)来实现这一点的示例。

  • %d will read the integer as it is the format specifier for integer %d 将读取整数,因为它是整数的格式说明符

  • Next we need to ignore the "f7hj-9" from the file so just writing it as it is will do the job接下来,我们需要忽略文件中的“f7hj-9”,因此只需按原样写入即可完成工作

  • 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)接下来我们需要读取 22 个空格,因此 %22c 将读取 22 个字符,而不管该字符是换行符还是空格(这里是 22 个空格)

  • Next we need to read a character so %c will store it in char c接下来我们需要读取一个字符,以便 %c 将它存储在 char c 中
  • Now another %*c will ignore the one whitespace after L现在另一个 %*c 将忽略 L 之后的一个空格
  • using %[^\\n]s will read the rest of the string until newline使用 %[^\\n]s 将读取字符串的其余部分直到换行


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


Input:输入:

 63f7hj-9 L Is this correct 63f7hj-9 L 这是正确的吗

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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