using eof on C++ - c++

i am looking for C++ coding for this pascal code
var
jumlah,bil : integer;
begin
jumlah := 0;
while not eof(input) do
begin
readln(bil);
jumlah := jumlah + bil;
end;
writeln(jumlah);
end.
i don't understand using eof on C++
it's purpose is to calculate data from line 1 to the end of the file
edit :
well i tried this but no luck
#include<iostream>
using namespace std;
int main()
{
int k,sum;
char l;
cin >> k;
while (k != NULL)
{
cin >> k;
sum = sum + k;
}
cout << sum<<endl;
}
sorry i am new to C++

You're pretty close, but probably being influenced a bit more by your Pascal background than is ideal. What you probably want is more like:
#include<iostream>
using namespace std; // Bad idea, but I'll leave it for now.
int main()
{
int k,sum = 0; // sum needs to be initialized.
while (cin >> k)
{
sum += k; // `sum = sum + k;`, is legal but quite foreign to C or C++.
}
cout << sum<<endl;
}
Alternatively, C++ can treat a file roughly like a sequential container, and work with it about like it would any other container:
int main() {
int sum = std::accumulate(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
0); // starting value
std::cout << sum << "\n";
return 0;
}

The usual idiom is
while (std :: cin >> var) {
// ...
}
The cin object casts to false after operator>> fails, usually because of EOF: check badbit, eofbit and failbit.

To format what David wrote above:
#include <iostream>
#include <string>
int main()
{
int jumlah = 0;
std::string line;
while ( std::getline(std::cin, line) )
jumlah += atoi(line.c_str());
std::cout << jumlah << std::endl;
return 0;
}
You can also find more information at http://www.cplusplus.com/reference/iostream/

Related

Optimize an algorithm to find multiple specific substrings of a string

I'm new to C++ coding and just started solving competitive programming problems. I want to solve the following task: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620.
I want to find a substring of a string. The problem is that the code below is slow and I fail the submission by getting the "time limit exceeded" "error". What can I do to speed up the code?
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
stringstream ss;
string m;
char prob[100000];
char substring[1000];
int howManyCases = 0;
int numberOfTests = 0;
cin >> numberOfTests;
cin.ignore();
while(numberOfTests--)
{
cin >> prob >> howManyCases;
while(howManyCases--)
{
cin >> substring;
if (strstr(prob,substring)) {
ss << 'y' << "\n";
}
else
{
ss << 'n' << "\n";
}
}
}
m = ss.str();
cout << m;
return 0;
}
i would make you of <algorithm> header:
std::string parent_string = "some string lala";
std::string sub_string = "lala";
auto found = parent_string.find(sub_string);
it will return iterator to where substring is. Then I wou;d use this clause:
if (found != std::string::npos) std::cout << "y\n";
else std::cout << "n\n";
If there is no limitation to the use of standard libraries, It's always a better choice to use it instead of creating your own algorithms (that may not handle some special cases you won't think of ).
Also, swap those huge ugly c-style arrays to std::string.

My question = until user press "enter" take average from user inputs in c++

This code calculates the average from user that user inputs integer until user inputs "666" integer. However, I want to make it stop when the user just presses the enter key. How can I achieve this?
#include <iostream>
using namespace std; //s
int main()
{
int total = 0, counter = 0, number, average;
do
{
cin >> number;
if(number == 666) //what should i do to make enter button instead of 666?
{
average = total / counter;
cout << average;
return 0;
}
total = total + number;
counter = counter + 1;
} while(1);
return 0;
}
Sadly, you cannot check that easily if the <ENTER> button has been pressed. cin reads formatted input (numbers in your case) and ignores everything else (including whitespaces, like newline). A solution to your problem is to read a whole line and extract the numbers from it:
#include <iostream> // cin, cout
#include <sstream> // istringstream
#include <string> // getline
int main()
{
// Reading a line from the standard input to the variable 'line'.
std::string line;
std::getline(std::cin, line);
// The easiest way to get the numbers from 'line' is to wrap it in an
// 'istringstream'. Now, you can use 'iss' just like 'cin'.
std::istringstream iss{line};
double total = 0.0;
double counter = 0.0;
for (double number; iss >> number; ++counter) {
total += number;
}
std::cout << "Avarage: " << total / counter << '\n';
return 0;
}
I have been found the solution:
note that I use Code::Blocks compiler and I had to make a adjustment.
Settings> compiler > tick on the """have g++ follow the c++11 ISO C++ language standard [-std=c++11]""" box and click OK.
solution is below:
#include <iostream>
#include <string>
using namespace std;
int main() {
float c = 0, sum = 0;
string input;
while (true) {
cout << "input number:";
getline(cin,input);
if (input == "") {
cout << "average:" << sum / c << endl;
break;
}
sum += stof(input);
c++;
}
return 0;
}

C++ simple string program

beginner here
i wrote the below in C++, it's a short program that currently takes 2 words as inputs, and outputs the same words back but the words are split into even and odd instead. I would like to be able to do this for 'T' words instead, but I can't figure it out. I would like to be able to first input the number of words that will follow, for example 10. Then to input the words and get T results back. So instead of just 2 words, an unlimited amount with the user specifying.
I need to put the below into a function and go from there sometime, but I want to learn the best technique to do so - any advice please?
Thanks!
Alex
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
Think I got it here, I was over-thinking this one
I put it in a for loop, as below - so any number of words can be input, user has to input the number of test cases at the
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++){
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
}
return 0;
}
Ultimately, you are performing the same task N times.
First, let's discuss how to store the information. Functionally, we have one string as input which yields two strings as output. std::pair (from <utility>) lets us easily represent this. But for sake of even-odd, std::array might be a better representation for us. Since we have a variable number of words as input, a variable number of std::array will be output. std::vector (from <vector>) is our friend here.
Second, let's discuss how to process the information. Using named variables for each output component does not scale, so let's switch to a fixed array (noted below as array<string,2>. By switching to a fixed array for output, addressing each split becomes a function of the loop index (index % 2). Below is a solution that generalizes on a known split size at compile time.
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}

C++ program to read a txt file and sort data

I'm a physics PhD student with some experience coding in java, but I'm trying to learn C++.
The problem I'm trying to solve is to read in data from a .txt file and then output all the numbers > 1000 in one file and all those <1000 in another.
What I need help with is writing the part of the code which actually reads in the data and saves it to an array. The data itself is only separated by a space, not all on a new line, which is confusing me a bit as I don't know how to get c++ to recognise each new word as an int. I have canabalised some code I have got from various sources online-
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include<cmath>
using namespace std;
int hmlines(ifstream &a) {
int i=0;
string line;
while (getline(a,line)) {
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a) {
int i=0;
char c;
a >> noskipws >> c;
while ((c=a.get()) && (c!=EOF)){
if (c==' ') {
i++;
}
}
return i;
}
int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "Input filename- ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()) {
goto start;
}
matos.seekg(0, ios::beg);
w = hmwords(matos);
cout << w;
/*c = hmchars(matos);*/
int RawData[w];
int n;
// Loop through the input file
while ( !matos.eof() )
{
matos>> n;
for(int i = 0; i <= w; i++)
{
RawData[n];
cout<< RawData[n];
}
}
//2nd Copied code ends here
int On = 0;
for(int j =0; j< w; j++) {
if(RawData[j] > 1000) {
On = On +1;
}
}
int OnArray [On];
int OffArray [w-On];
for(int j =0; j< w; j++) {
if(RawData[j]> 1000) {
OnArray[j] = RawData[j];
}
else {
OffArray[j] = RawData[j];
}
}
cout << "The # of lines are :" << l
<< ". The # of words are : " << w
<< "Number of T on elements is" << On;
matos.close();
}
But if it would be easier, i'm open to starting the whole thing again, as I don't understand exactly what all the copied code is doing. So to summarise, what I need is it to-
Ask for a filepath in the console
Open the file, and store each number (separated by a space) as an element in a 1D array
I can manage the actual operations myself I think, if I could just get it to read the file the way I need.
Thanks very much
Using C++11 and the Standard Library makes your task fairly simple. This uses Standard Library containers, algorithms, and one simple lambda function.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string filename;
std::cout << "Input filename- ";
std::cin >> filename;
std::ifstream infile(filename);
if (!infile)
{
std::cerr << "can't open " << filename << '\n';
return 1;
}
std::istream_iterator<int> input(infile), eof; // stream iterators
std::vector<int> onvec, offvec; // standard containers
std::partition_copy(
input, eof, // source (begin, end]
back_inserter(onvec), // first destination
back_inserter(offvec), // second destination
[](int n){ return n > 1000; } // true == dest1, false == dest2
);
// the data is now in the two containers
return 0;
}
Just switch the type of variable fed to your fistream, created from new std:ifstream("path to file") into a int and c++ will do the work for you
#include <fstream> //input/output filestream
#include <iostream>//input/output (for console)
void LoadFile(const char* file)
{
int less[100]; //stores integers less than 1000(max 100)
int more[100]; //stores integers more than 1000(max 100)
int numless = 0;//initialization not automatic in c++
int nummore = 0; //these store number of more/less numbers
std::ifstream File(file); //loads file
while(!file.eof()) //while not reached end of file
{
int number; //first we load the number
File >> number; //load the number
if( number > 1000 )
{
more[nummore] = number;
nummore++;//increase counter
}
else
{
less[numless] = number;
numless++;//increase counter
}
}
std::cout << "number of numbers less:" << numless << std::endl; //inform user about
std::cout << "number of numbers more:" << nummore << std::endl; //how much found...
}
This should give you an idea how should it look like(you shoudnt use static-sized arrays tough) If you got any probs, comment back
Also, please try to make nice readable code, and use tabs/ 4 spaces.
even though its pure C, this might give you some hints.
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#define MAX_LINE_CHARS 1024
void read_numbers_from_file(const char* file_path)
{
//holder for the characters in the line
char contents[MAX_LINE_CHARS];
int size_contents = 0;
FILE *fp = fopen(file_path, "r");
char c;
//reads the file
while(!feof(fp))
{
c = fgetc(fp);
contents[size_contents] = c;
size_contents++;
}
char *token;
token = strtok(contents, " ");
//cycles through every number
while(token != NULL)
{
int number_to_add = atoi(token);
//handle your number!
printf("%d \n", number_to_add);
token = strtok(NULL, " ");
}
fclose(fp);
}
int main()
{
read_numbers_from_file("path_to_file");
return 0;
}
reads a file with numbers separated by white space and prints them.
Hope it helps.
Cheers

using fflush on C++

Can someone help me using fflush in C++
Here is a sample code in C
#include <stdio.h>
using namespace std;
int a,b,i;
char result[20];
int main() {
scanf("%d %d\n", &a, &b);
for (i=1; i<=10; i++) {
printf("5\n");
fflush(stdout);
gets(result);
if (strcmp(result, "congratulation") == 0) break;
}
return 0;
}
This is program for getting interactive input.
I usually use cin and cout so is it possible not using printf and scanf?
The translation to C++ programming style is this:
#include <iostream>
using std::cin;
using std::cout;
using std::string;
int main() {
string line;
int a, b;
if (cin >> a >> b) {
for (int i = 0; i < 10; i++) {
cout << "5" << std::endl; // endl does the flushing
if (std::getline(cin, line)) {
if (line == "congratulations") {
break;
}
}
}
}
return 0;
}
Note that I deliberately added some error checking.
Although I haven't completely understood your question, the C++ version of your program would be something like this (assuming hasil should be result):
#include <iostream>
int main() {
int a,b,i;
std::string result;
std::cin >> a >> b;
for (i=1; i<=10; i++) {
std::cout << "5" << std::endl;
std::cin >> result;
if (result == "congratulation") break;
}
return 0;
}
Note, that std::endl is equivalent to '\n' << std::flush and therefore both puts the line end and calls .flush() on the stream (which is your fflush equivalent).
Actually to get the real equivalent to your scanf call (and not press enter between a and b), you would have to do something like:
#include <sstream>
...
std::string line;
std::cin >> line;
std::istringstream str(line);
str >> a >> b;
If you have need for C IO facilities, include <cstdio>. You now have std::printf and std::fflush etc. You might consider calling std::ios::sync_with_stdio() if you want to use C IO and iostreams interwovenly.