Witam,
Mam następujący problem otóż nie wiem jakich operacji dokonać aby mając liczby z pliku np
2 1 -5 6
-1 5 7 -6 5
zsumować wszystkie pola wierszy i wypisać tą sumę dla każdego wiersza. Ktoś mógł by podsunąć pomysł jak tego dokonać?
Wczytaj wiesz. Konwertuj napisy na liczby. Sumuj. Powtórz dla każdego wiersza.
c: fgets
(czytanie wiersza) + strtol
(parsowanie kolejnych liczb wiersza)
c++: getline(filestream,string)
(czytanie wiersza) + stringstream
(parsowanie kolejnych liczb wiersza)
Wg mnie jest prostszy sposób:
#include <cctype>
#include <iostream>
using namespace std;
istream &WS(istream &s)
{
while((s)&&(isspace(s.peek())))
{
if(s.get()=='\n')
{
s.clear(ios::failbit);
break;
}
}
return s;
}
int main()
{
int sum=0,x;
while(cin>>x)
{
sum+=x;
if(!(cin>>WS))
{
cout<<"Sum: "<<sum<<endl;
sum=0;
cin.clear();
cin>>ws;
}
}
return 0;
}
Otagowane jako C, ale @_13th_Dragon zaczął się w C++ bawić, więc ja też dwoje 3 grosze dorzucę. :)
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <vector>
template<typename T>
std::vector<T> sumRows(std::istream& is) {
std::vector<T> sums;
std::string line;
while (std::getline(is, line)) {
std::istringstream is(line);
sums.push_back(std::accumulate(std::istream_iterator<T>(is), std::istream_iterator<T>(), T()));
}
return sums;
}
int main() {
std::vector<int> sums = sumRows<int>(std::cin);
std::copy(sums.begin(), sums.end(), std::ostream_iterator<int>(std::cout, "\n"));
}
OK, dawno w C się nie bawiłem, ale spłodziłem coś takiego:
#include <stdio.h>
#include <ctype.h>
#define ROW_MAX 100
const char* firstNotOf(const char* str, int (*f)(int)) {
const char* res = str;
while (*res != '\0' && f(*res))
++res;
return res;
}
int sumRow(const char* row) {
int n, sum = 0;
const char* ptr = firstNotOf(row, isspace);
while (*ptr != '\0') {
if (sscanf(ptr, "%d", &n) > 0)
sum += n;
/* go to next token */
ptr = firstNotOf(ptr, isgraph);
ptr = firstNotOf(ptr, isspace);
}
return sum;
}
int main() {
char row[ROW_MAX];
while (fgets(row, ROW_MAX, stdin) != NULL)
printf("%d\n", sumRow(row));
return 0;
}
@rincewind, znowu przekombinowałeś, prostsze oraz bez ograniczeń do rozmiaru wiersza:
#include <ctype.h>
#include <stdio.h>
int wslf()
{
int ch=0;
while(isspace(ch=getc(stdin))) if(ch=='\n') return 1;
if(ch!=EOF) ungetc(ch,stdin);
return 0;
}
int main()
{
int sum=0,x;
while(scanf("%d",&x)==1)
{
sum+=x;
if(wslf())
{
printf("%d\n",sum);
sum=0;
}
}
return 0;
}
@_13th_Dragon: Co do przekombinowania – może coś takiego? :P
#include <stdio.h>
#include <ctype.h>
#define U(c) ungetc(c,stdin)
int main(){int c,S=0,n=0,s=0;while((c=getc(stdin))!=EOF){isblank(c)?S+=(s?-1:1)*n,n=s=0:isdigit(c)?n*=10,n+=c-'0':c=='-'?(n>0?U(c),U(' '):(s=1)):c=='\n'?printf("%d\n",S+(s?-1:1)*n),S=n=s=0:c!='+'?S+=(s?-1:1)*n,n=s=0:U(' ');}return 0;}
Co najpiękniejsze, kompiluje się bez warningów z -Wall -Wextra -pedantic
. Wygląda na to, że do Brainfucka niedaleka droga. ;)
ale kombinujecie:
http://ideone.com/X9Nwxb