End of File (EOF) - c++

Hello I've written an algorithm where it prints last number , but I wonder how to make it not to print default value of "number" for example(4.94066e-324) when there's no number written in console/file.
#include <iostream>
using namespace std;
int main() {
double number;
for (; cin >> number;);
cout << number; }

One way is to check wether the first input operation succeeds or not:
#include <iostream>
int main() {
double number;
if(std::cin >> number)
{
while (std::cin >> number);
std::cout << number;
}
else
{
std::cout << "There is no number :(";
}
}
Few things I changed here:
removed using namespace std;, it's considered bad parctice
a while is better suited for this task than a half-empty for
And of course this can be generalized to any std::basic_istream.

You can use a flag to check if you have ever got any input, like this:
#include <iostream>
using namespace std;
int main() {
double number;
bool flag = false;
for (; cin >> number;)
flag = true;
if(flag)
cout << number;
}

Related

Convert char array to a string with cin.getline(.)

hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}

C++ test CIN on one line

I've recently started teaching myself C++, and after having written a lot of user input code, it's made me wonder if there's a simpler way of handling it.
For example, the normal way of doing it would be like this:
#include <iostream>
using namespace std;
int inp;
int guess = 13;
void main(){
cout << "Guess a number: ";
cin >> inp;
if (inp == guess)
cout << endl << "Nice.";
}
But what I want to do is:
#include <iostream>
using namespace std;
int guess = 13;
void main(){
cout << "Guess a number: ";
if (cin == guess)
cout << endl << "Even nicer.";
}
Is there a way to do this? Or this that just improper C++ standard?
In short: No, it's not possible to do as you want it.
You need to understand, that >> is actually a function call of
template<typename T>
std::istream& operator>>(std::istream& is, T& result);
and == is a function call to
template<typename T>
bool operator==(const std::istream&,const T& x);
Where the latter is used to check the stream state, and doesn't extract any user input.
To compare the input the result needs to be extracted from the std::istream in 1st place.
Well you can do it in one line but you don't really need to. But here are some examples anyway
//This will work for a char
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char test = 'a';
if (getch()== test)
cout<<"\n Works";
return 0;
}
And if you really want
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x =1;
int y;
for( cin >> y ; x == y ; )
{
cout<<"\n Works";
break;
}
return 0;
}
Or as NathanOliver said you could simply do this
if( cin >> inp && inp == guess )
But really you want to keep it simple as this will confuse others as well as yourself after some time. You want to leave your code as easy as possible

Using the getword function c++

Am I using the getword function wrong here? The compiler keeps telling me that there is no member function.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
int OccuranceOfString(ofstream & Out)
{
string Occur;
string Temp;
int OccurLength;
int count;
cout << "please enter to string to search for";
cout << endl;
cin >> Occur;
OccurLength = Occur.length();
while(Out.getword(Temp))
{
if (Temp == Occur)
{
count ++;
}
}
return count;
}
Whats wrong with my code? I'm trying to find all occurances of a string with this function
std::ofstream has no getword function: see here.
Perhaps you're thinking of std::getline.
There is no function getword in the header files listed. You simply must construct a function that will extract words from a line. capture a line by
getline(out,line);
line will have your line of string and use line[index] to get continuous characters to be equal to a word.
You can use this
std::string::find
do something like this..
int pos = 0;
int occurrences = 0
string input = "YAaaaAH";
string find = "a";
while(pos != -1){
pos = input.find(find,pos);
occurrences++;
}
text file :
code :
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream file("DB_name_age.txt");
int index;
string name;
int age;
if(file.is_open())
{
while(file >>index >> name >>age)
{
cout << index <<" "<<name <<" "<<age << endl;
}
}else{
cout<< "file open fail" <<endl;
}
return 0;
}
visual explanation:

for loop's init-statement with two types of variable

I want to declare two types of variables in for's init-statement. like the following codes. I know "for (string word, int numb, ; cin>>word>>numb; )" is not working. just trying to let you know what I am trying to do. My goal is to declare two types of variables with the same lifetime and cin them together. Other way of coding is helpful too. thanks in advance.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
cout<<"enter a word and a number"<<endl;
for (string word, int numb, ; cin>>word>>numb; )
{
//do some work
}
return 0;
}
ok, I think this is the closest I can get as someone suggested.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
vector<pair<string,int> > pvec;
cout<<"enter a word and a number"<<endl;
{
int numb=0;
for (string word; cin>>word>>numb; )
pvec.push_back(make_pair(word,numb));
}
cout<<pvec[3].second<<endl;
return 0;
}
About the nearest you can get is:
int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
for (int numb; cin>>word>>numb; )
{
//do some work
}
}
return 0;
}
The extra set of braces limits the scope of word similarly to the way the loop limits the scope of numb. Clearly, you could reverse the declarations; it might be better (more symmetric) to use:
int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
int numb;
while (cin>>word>>numb)
{
//do some work
}
}
return 0;
}
Since there is no increment or initialize operation, the code is really a while loop with a couple of declared variables; this achieves the same result and works.
This is not possible. You can declare two variables of the same basic type in the initialization statement in the for loop, but you cannot declare two variables of different basic types. You have to declare one outside of the for loop.
I'm fairly certain it's not possible to declare 2 variables of 2 different types in a for statement, but I also fail to see the advantage to doing so over something like this:
int main ()
{
cout<<"enter a word and a number"<<endl;
while( cin.good() )
{
string word;
int num;
cin >> word >> num;
//do some work
}
return 0;
}
In general I prefer to use for loops where there is something to count or at least iterate over. Other situations should be using a while or do loop.
The way you are trying to do it is not the cleanest way. I'd do it like this:
string word;
int num;
while(true)
{
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
word and num are in the same scope (same "lifetime")
Note that you'd want to substitute the while(true) with some suitable condition.
If you want word and num to be inside the scope of the loop do something like:
while(true)
{
string word;
int num;
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
OR
{
string word;
int num;
while(true)
{
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
}
I don't know why this would be necessary though.
The following is untested, but should work:
int main()
{
std::cout << "enter a word and a number" << endl;
for (struct { std::string word, int number } vars;
std::cin >> vars.word >> vars.number;
)
{
//do some work
}
return 0;
}
Since c++17:
#include <iostream>
#include <tuple>
int main() {
for (auto && [w,i] = std::tuple{std::string{},int{}} ; std::cin >> w >> i ; )
std::cout << "word " << w << " number " << i << "\n";
return 0;
}

using eof on 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/