标题:NKOJ 1023: A+B+C+D+... 的挑战
取消只看楼主
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
 问题点数:0 回复次数:4 
NKOJ 1023: A+B+C+D+... 的挑战

This is an annoying problem. How do you handle the newline char '\n' in the input stream?

Although my C++ code was accepted, I am not satisfied --- I used cin.peek(). So the qeustion remains to be

1. Can you do it in C?
2. Can you do it without using cin.peek() and/or putback()?

Note that there maybe more than one spaces between two numbers, and there maybe 0 or more spaces before '\n'.


Problem statement:

http://acm.nankai.edu.cn/p1023.html

对于输入的数据进行求和。

Input
输入有多行数据,每行有若干整数,这些整数数以空格分割,请分别求出每行整数的和。

Output
输出的每行对应输入的每行,每行一个数字,即为输入的一行整数之和。

Sample Input
100 200 4
45 45

Sample Output
304
90

[此贴子已经被作者于2007-7-19 8:02:19编辑过]

搜索更多相关主题的帖子: NKOJ 挑战 
2007-07-19 07:59
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
以下是引用leeco在2007-7-19 13:49:00的发言:
1023 Accepted GNU C 0.29k 0ms 672KB 2007-07-19 13:45:05

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n,res;
char buf[10000],*p;
while(gets(buf)){
sscanf(strtok(buf,\" \n\"),\"%d\",&res);
while(p=strtok(NULL,\" \n\")){
sscanf(p,\"%d\",&n);
res+=n;
}
printf(\"%d\n\",res);
}
}

very smart soln --- thought there is some obvious solution, but it seems it is not that obvious.

Here is my C++ version (I thought those who are interested in this problem already tried it)


#include <iostream>
using namespace std;

int main()
{
int a, sum=0;

while( cin>> a )
{
sum += a;
while(cin.peek() == ' ')
getchar();
if(cin.peek() == '\n')
{
cout<<sum<<endl;
sum = 0;
}
}

return 0;
}



I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-07-19 16:18
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
mp3aa:

seems to be a good idea.

tried you soln, does not handle the case in which you have spaces before '\n' well, say

4 5 6 '\n'
1 2 3

I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-07-20 05:06
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
you are not asked to deal with overlfow --- instead the main prolbem is to handle the '\n' in the input stream.


I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-07-20 15:20
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
1 2 3
6
4 5
9
9 10
19
11 13 '\n' (note there are 3 spaces before '\n')

Your program for the final test input results in a dead loop.

I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-07-20 20:03



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-156451-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.084459 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved