码迷,mamicode.com
首页 > 其他好文 > 详细

函数sscanf()及sprintf()的简单讲解 --- NOJ 2015 PUMA

时间:2016-05-12 14:47:48      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

本次讲解将结合NOJ-2015和cplusplus.com的讲解进行,
题目链接如下:
http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=2015
cplusplus的地址:
http://www.cplusplus.com/

从字面理解这两个函数的意思分别是从字符串读入输出到字符串,即
Read formatted data from stringWrite formatted data to string;
顾名思义,对sscanf()如果你想输入了一个字符串,你想从里面提取一些数据,如int型数,double型,字符子串等,就可以使用了。对sprintf(),就是生成一个字符串,可以使用你想生成的数据进行组合。

一定注意两个函数的返回值~~

对sscanf():
On success, the function returns the number of items in the argument list successfully filled. This count can match the expected number of items or be less (even zero) in the case of a matching failure.
In the case of an input failure before any data could be successfully interpreted, EOF is returned.
即返回成功读入的变量的数目。

对sprintf():
On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.
On failure, a negative number is returned.
即返回成功赋值的所有字符长度。

具体见示例代码(有删改):

sscanf()的示例代码:

#include <stdio.h>
int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;
  int n=sscanf (sentence,"%s %*s %d",str,&i); //%*s表示跳过这个变量(注1printf ("%s -> %d\n",str,i);
  printf("%d\n",n);

  return 0;
}

Output:
Rudolph -> 12
2
//即表示成功读入了2个变量

%*s 的用法见:http://blog.csdn.net/why850901938/article/details/51298656

sprintf()的示例代码:

/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

Output:
[5 plus 3 is 8] is a string 13 chars long
//空格算入了字符数量

最后来看这个题目,只有从输入的字符串中提取数据,才能进行接下来的运算。
所以使用sscanf()进行操作。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int pri,num,zhe;
char a[20];
double sum;
int main()
{
    int T;
    scanf("%d",&T);
    getchar(); 
    for(int i=0;i<T;i++)
    {
        gets(a);
        int l=strlen(a);
        if(a[l-1]==‘%‘)
        {
            a[l-1]=‘\0‘;
            sscanf(a,"%d %d %d",&pri,&num,&zhe);
            sum+=pri*num*(100-zhe)*0.01;
        }
        else 
        {
            sscanf(a,"%d %d",&pri,&num);
            sum+=pri*num;
        }
    }
    printf("%.2lf\n",sum);
    return 0;
}

仅代表个人观点,欢迎交流探讨,勿喷~~~

技术分享

PhotoBy:WLOP

http://weibo.com/wlop

函数sscanf()及sprintf()的简单讲解 --- NOJ 2015 PUMA

标签:

原文地址:http://blog.csdn.net/why850901938/article/details/51365201

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!