如何只用C ++中的输入文件读取数字? [英] How to only read numbers from a input file in C++?

查看:125
本文介绍了如何只用C ++中的输入文件读取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在我的C ++类中到期的作业,我被指示创建一个C ++代码,该代码从包含此信息的.dat文件中读取相同的格式:



For an assignment due in my C++ class I am instructed to create a C++ code that reads from a .dat file containing this info in the same format:

T-Shirt:
15
Jeans:
60
Jacket:
80
Sweatshirt:
30
Hoodie:
40
Socks:
15
Discount:
10





我想知道是否有人可以向我解释如何编写只读取数值而不是字符值的代码。非常感谢。



我尝试过:



我在谷歌和其他论坛上四处看看,我找不到我想要的东西。我的教授没有给我们任何关于这方面的信息,我已经多次阅读了指定的章节。



I was wondering if anyone could explain to me how to write a code that will only read the number values rather than the character values. It would be much appreciated.

What I have tried:

I've looked around on google and other forums and I can't quite find what I'm looking for. My professor didn't give us any information on this and I've read the assigned chapters a couple of times.

推荐答案

因为它是一个文本文件,你必须先阅读文字。逐行阅读文本文件是一项常见任务,并由大多数教程处理。



如果您知道文件格式,就像您的情况一样,您可以处理每一行并解析它根据内容。有两种C标准库函数可以从文本转换整数: atoi - C ++ Reference [ ^ ]和strtol - C ++参考 [ ^ ]。



还要看一下上面链接的左侧。它们按顶部的标题/任务列出库函数,并在底部列出所选标题的函数。您应该熟悉标准库函数,以了解哪些可能用于您将来的问题。



因为这是一项任务,所以我不会给你代码。但你应该能够继续上述信息。
Because it is a text file you have to read text first. Reading text files line by line is a common task and handled by most tutorials.

If you know the file format like in your case you can then process each line and parse it according to the content. There are two kinds of C standard library functions that can convert integers from text: atoi - C++ Reference[^] and strtol - C++ Reference[^].

Have also a look at the left side of the above links. They list the library functions by header / task on the top and the provided functions for the selected header on the bottom. You should become familiar with the standard library functions to know which might be used for your future problems.

Because it is an assignment I will not give you code. But you should be able to proceed with the above information.


引用:

我想知道是否有人可以向我解释如何编写一个只读取数值而不是字符值的代码。非常感谢。

I was wondering if anyone could explain to me how to write a code that will only read the number values rather than the character values. It would be much appreciated.



1)作为一个整体或第1行读取文件。

2)每行检查数字或不是
3)如果是数字,那就做你需要的。


1) read the file either as a whole or lines 1 by 1.
2) for each line check if number or not
3) if number, do what you need to.


这篇关于如何只用C ++中的输入文件读取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆