this code compiles on my computer and runs but not on server [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I wrote a C++ program using codeblocks and at the last minute I decided to use empress, the server at school that we use to do our labs, and turns out that it did not work! What does that mean? Is my program not right? Or could it be a compiler issue? I normally use linux ubuntu using codeblocks to do my programming. I tested the program using windows and it also worked. Why doesn't it run on the server?
Here is the code that I think causes the problem:
bool dictionary::insertWordsIntoDict(string fileName)
{
ifstream inp;
string word;
vector<string> vec;
inp.open(fileName.data());
if(inp.good())
{
while(!inp.eof())
{
inp>>word;
vec.push_back(word);
}
string temp;
string temp2= "#.txt";
for(int i=0 ; i<vec.size() ; i++)
{
temp = vec[i];
temp2[0] = tolower(temp[0]);
cout<<temp<<endl;
AddWord(temp.data(), temp2);
}
}//end of if statement
else
{
cout<<":( File does not exist! "<<endl;
return failure;
}
}// end of function insert words

while(!inp.eof()) is not a good way to read from a file. In particular, if it cannot read for some reason other than EOF, the condition will never be false, and your loop will run forever.
The correct way to write this kind of loop is:
while(inp >> word)
{
vec.push_back(word);
}
Here, inp >> word will evaluate to false if word could not be read from the input stream for any reason.
I can't be sure this is your problem without more details, but it can't hurt.

Well there is at least one issue, you are using eof in your loop condition, you should modify like so:
while( inp >> word)
{
vec.push_back(word);
}
This previous thread covers why Why is iostream::eof inside a loop condition considered wrong?.

Related

How to implement a semicolon ends the input in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to implement a command line interface, the command must end with semicolon. Then press enter to execute. Otherwise, press enter wraps the line. If I don't descirbe it clearly, you can refer to the mysql command line.
How to implement the above in C++? For example:
If user inputs foo;bar then str = "foo". It can have some spaces in between ;.
In C++ IO I just know:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
}
I don't know how to implement other input function.
The most simple approach would be to use std::getline (as adviced in comments), but with a custom delimiter (';' in your case) like this:
string command;
while (getline(cin, command, ';')) {
// process the command there
}
However, this approach has several drawbacks and is pretty limited:
it reads until any ';' is hit. If you're going to process commands complicated enough to support string literals, then you will need more complicated parsing to handle this: echo "Hello; sample text"; exit;, as two commands, but not three;
when you hit Enter, getline will wait for more input until it sees a semicolon, but it will not insert any 'user-friendly' prompt like > to let the user know that they need to supply more input or that they forgot the semicolon at the end of command.
If you're ok to go without supporting these features, getline is quite good to go. Otherwise you'll need to parse your input lines by yourself.
I guess this is what you want to do:
#include <iostream>
int main() {
std::string command;
bool flag = true;
do
{
std::string str;
std::getline(std::cin,str);
for(int i = 0; i < str.length(); i++)
{
if(str[i] == ';')
{
str = str.substr(0,i+1);
flag = false;
}
}
command += str;
} while(flag);
}

C++ Xcode won't run my for loop (very short) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to continue reading Stroustrup PPUC++, but I'm stuck! I wrote a BleepOutTheBadWords program a few days ago and it worked. I tried to write the program with my younger brother a few days ago and I failed. This is essentially a program I wrote to figure out what is going wrong. It is not printing out each word in the "sentence" vector.
#include <iostream>
#include "std_lib_facilities.h" // Stroustrup header file
using namespace std;
int main()
{
cout << "Write a sentence." << endl;
vector<string> sentence;
// Put user input into "sentence" vector
for (string word; cin >> word; )
sentence.push_back(word);
// Print each word in "sentence" vector
for (int i = 0; i < sentence.size(); ++i)
cout << sentence[i] << endl;
// Keep window open and return 0 to show program succeeded
keep_window_open();
return 0;
}
The answer is going to be obvious. Please just state the obvious if you are so kind. I looked through the suggested readings on two different pages before posting this.
XCode won't run my for loop
Your loop is running. The thing that you missed is how to terminate the loop.
for (string word; cin >> word; )
This loop will terminate when cin >> word evaluates to false. Normally, i.e. without an error condition, it will evaluate to false when your input is finished. The exact process to signal an end of stream, or EOF, is platform dependent. If you are running this program on OSX then the most common way to signal EOF is to hit Ctrl + D button, unless you changed the default configuration of your keyboard. Once you signal EOF this input loop will terminate and you will be able to see the output.
I'm pretty much sure that Stroustrup discussed this on his book (though I can not refer to an exact page number). However "Chapter 10: Input and Output Streams" of his books covers these things in detail.

Making a password type program that needs to accept letter and number combinations? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am making a shopping list program. For this program, I need to be able to type in a user input that accepts both number (1564, 121,1, etc) and word (hello, goodbye, etc) combinations. The program reads numbers just fine, but it cannot process words. Thank you in advance. The part of the code I am stuck with is below:
int code, option, count = 0;
double quantity, price, cost;
string description;
cin >> code;
while ((code != 123456789) && (count < 2))
{
cout << "Incorrect code, try again \n";
cin >> code;
count++;
if (count == 2)
{
cout << "max # of tries reached. Goodbye. \n";
system("pause");
}
}
Your code variable is now an int. If you wanted that to be a string, declare it so: std::string code;. Note that you might need to #include <string> in the very beginning. Also, if you want to compare it with numbers, either you call something like atoi() (string has .cstr()), or better yet, you might just compare it with "123456789". HTH.

user enters String instead of Int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We have tried to search this problem but we haven't found any answers. If The user inputs a string variable when the system requires a integer how do you evade the problem with out using a while loop?
{
int grade_var=0,grade_1=0,sum=0;
cout<<"Enter the number of grades you have:\t";
cin>>grade_var;
for(int i=1;i<=grade_var;i++)
I don't wish to do a while loop for my program has a lot of integer insertions and want to know an easier way to correct rather than while loops?
While loops are generally the way to go.
However, to keep the code clean, you may want to consider putting said while loop into a helper function, so you can just call PollForIntegerInput(string prompt) from anywhere in your code, and then handle that input in one place. There is almost never a reason you should be duplicating an input loop like that.
As for a truly nonlooping answer, I have none.
Calling operator>> on a stream returns the stream itself, which can be converted to bool to check if the stream is in a good state. If a bad extraction happens, the stream is not in a good state. So you can do something like this:
if (cin >> grade_var)
This will check that it was successful. You can just negate the condition to find it if it wasn't successful. How you handle this condition is up to. Maybe you'll return early on failure. If you want to reprompt the user for correct input, however, you'll need a loop.
It's not too clear what your problem is, but...
It's almost always poor design to input the number of data
points which will follow. If you expect a series of int, for
example:
std::vector<int> grades;
int grade;
while ( std::cin >> grade ) {
grades.push_back( grade );
}
It doesn't get much simpler.
If you do want to insist on an exact number of input, outputting
an error when the user inputs something incorrect, the usual
pattern would be:
std::vector<int> grades;
while ( grades.size() != targetNumber ) {
int grade;
while ( !(std::cin >> grade) ) {
std::cout << "Integer wanted" << std::endl;
std::cin.clear();
std::cin.ignore( INT_MAX, '\n' );
}
grades.push_back( grade );
}
Still no for. (In fact, for loops with input are very, very
rare.)

Skip last K lines while traversing a file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A user had posted a similar question earlier this day which was very soon closed due to its vagueness. Thus re-posting the question in detail with a solution as I didn't find a specific article dealing with it on the internet.
The requirement is to read and print all lines of a file except the last K.
Suppose a file contains text as:
Hello there!
My name is
Mr. XYZ
I like playing football
And if K is 2, then it should print all the lines except the last 2. i.e.:
Hello there!
My name is
Why not simply put lines into a std::deque and dump one element when its size is greater k ?
#include<iostream>
#include<fstream>
#include<deque>
int main()
{
std::fstream fs;
fs.open("output.txt",std::ios::in);
std::deque<std::string> deq;
std::string str;
int k=2;
while(std::getline(fs,str))
{
deq.push_back(str);
if(deq.size() > k)
{
std::cout <<deq.front()<<std::endl;
deq.pop_front();
}
}
}
This can easily be solved by creating a window of size K and then traversing the file till the right end of the window reaches the end of the file. The basic steps being:
Traverse the first K lines of the file without printing it.
Open the same file using another stream object.
Now simultaneously traverse both the streams so that fisrt stream is always K lines ahead of the second stream.
Run a loop while the second first stream is valid. In the loop, read through the first stream as well and keep print the lines.
The code would be
#include<iostream>
#include<fstream>
#include<string>
int main()
{
fstream fs;
fs.open("abc.txt",ios::in);
string str;
int K = 2;
while(getline(fs,str) && K>1)
{
K--;
}
if(K==1)
{
fstream fsNew;
fsNew.open("abc.txt",ios::in);
while(getline(fs,str))
{
getline(fsNew,str);
cout<<str;
}
}
cin.ignore();
}