My codes work well In Dev c++ IDE, but in linux terminal, it doesn't. (especially in the part of 'while' loop.) [closed] - c++

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 6 years ago.
Improve this question
while(true) {
getline(myfile, a[i]);
if (a[i]=="")//or if(a[i].empty())
break;
i++;
n = i;
}
In this while loop, when getline function gets a blank line from myfile object (there is a blank line between a series of binary numbers).
Example:
101010
000
11
1
00
<- when getline meets this line, by "if" break; has to work.
0011
10
00111
1101
But, it doesn't realize that blank line.
What is wrong?
What should I code to break when getline() meets the blank line?
I do this through PuTTY.

You are most likely running into the NL/CR issue.
Instead of
if (a[i]=="")
Use something like:
if (isEmptyLine(a[i]))
where
bool isEmptyLine(std::string const& s)
{
for ( auto c : s )
{
if ( !std::isspace(c) )
return false;
}
return true;
}
You can also convert the file into a file with UNIX style line endings by using a utility called dos2unix. That should also fix the problem.

Related

What is the problem with the following c++ code? [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 2 years ago.
Improve this question
The problem is 12289 - One-Two-Three from Online Judge at https://onlinejudge.org/external/122/12289.pdf
I have to compare a given string s with the following: "one","two","three", and return a number that indicates which of those has the most correct characters in a correct position with the string.
The following is my attempt at getting an accepted answer.
#include <cstdio>
using namespace std;
int main(){
char c;
int t,len,c1,c2;
scanf("%d\n",&t);
while(t--){
len = 0;
c1 = 0;
c2 = 0;
while(true){
scanf("%c",&c);
if(c=='\n') break;
if("one"[len] == c) c1++;
if("two"[len] == c) c2++;
len++;
}
if(len>3) printf("%d\n",3);
else if (c1>c2) printf("%d\n",1);
else printf("%d\n",2);
}
printf("\n");
}
I am getting a "Wrong answer" in this question, that usually does not involve formatting problems. I am new to C++ so it would help me a lot to know in what can I improve.
As Thomas says, you should check if len is > 3. Strings are basically character arrays terminated by the null byte or '\0'. In memory this is represented as ['o', 'n', 'e', '\0', ?, ...] wherein the ? is garbage value or, as C/C++ calls it, illegal memory access. So, there is a chance that "one"[4] == c or "two"[4] == c to be true since we do not know the value stored there. If that happens then the line
else if (c1>c2) printf("%d\n",1);
would have a problem.
Thank you for your support. I discovered that the real problem was the formatting of the input. There were blank lines between two consecutive inputs, so the part of if(c=='\n') break; was causing some trouble.
Anyways, I will try to remake the solution following C++ guidelines. I just did not know how to process a string, so I thought of doing it character by character. I'm closing the thread.

Remove whitespace in C++ string doesn't work [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have read these two questions already:
Remove spaces from std::string in C++
remove whitespace in std::string
For some reason, I can never get the solutions to work correctly. In my program, I collect input from the user and pass it to an std::string. From there, I want to remove all of the spaces in it. For example, if the user inputs "3 + 2", I would like it to change to "3+2".
What happens is, whatever is before the first string is kept. Here is my program:
#include <iostream>
std::string GetUserInput() {
std::cout << "Please enter what you would like to calculate: ";
std::string UserInput;
std::cin >> UserInput;
return UserInput;
}
int PerformCalculation(std::string Input) {
Input.erase(std::remove_if(Input.begin(), Input.end(), ::isspace), Input.end());
std::cout << Input;
return 0;
}
int main() {
std::string CalculationToBePerformed = GetUserInput();
int Solution = PerformCalculation(CalculationToBePerformed);
return 0;
}
So when I run this program and type in "3 + 2", the output is "3".
Here is my console:
Please enter what you would like to calculate: 3 + 2
3
Process finished with exit code 0
I cannot figure out how to resolve this. I even tried using a solution that involved using a regex to remove all the \s characters, and that gave me the same issue.
To read the complete line (up to terminating \n), you need to use e.g. std::getline(std::cin, UserInput);. Otherwise, you're currently reading text up to first whitespace character.

what is the time complexity of this program? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I'm new to time complexity in algorithms.
This is the code for counting the number of words in a text file.
My problem is that every time my program prints one more than the actual count of words in the file, like if I have 11 words in my file it prints 12.
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
/* main function */
void main()
{
ifstream inFile; //file file name
string fileName;
string word;
int count = 0;
inFile.open("example.txt");
while(!inFile.eof())
{
inFile >> word;
++count;
}
cout << "Number of words in file is " << count<<endl;
inFile.close();
}
//this file is for counting the number of words in a text file**
First thing first : Why is iostream::eof inside a loop condition considered wrong? This will answer your extra count problem.
Then, coming to complexity, since it will go though every N words till it reaches end of file, it will be done in O( N ) time
Also, void main() is not legal c++, main should return int

Can't read from file all integers of a line (ifstream) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This function is supposed to open a .txt file like this:
1 4 5
2 4 6
etc. (with tab between numbers)
and save each number in one variable
void Graph::readData(char* fname)
{
//cout<<"1";
int x,y,w;//assistant variables
ifstream input;//stream for reading file
input.open(fname,ios::in);
if(!input)
{
cerr<<"Input file doesn't exist"<<endl;//error if file doens exist
}
else
{
cout<<"Input file opened"<<endl;
cout<<"Reading Data from file..."<<endl;
while(!input.eof())//till the end of file
{
input>>x>>y>>w;//reads the links-site
cout<<"x: "<<x<<"y:"<<y<<"w: "<<w<<endl;
insertLink(x,y,w);//inserts them
}
input.close();//closing file
}
}
However, when I "cout" the results I get something like this:
x=1 y= w=5
x=2 y= w=6
without y!
Why could this happen?
PS: In addition, eof() becomes true after the file is finished (reads one extra line). How can I stop while iteration properly?
This is the file I'm trying to read from: http://www.speedyshare.com/tpvuD/input.txt
To stop the iteration properly, write the loop as:
while(input>>x>>y>>w)//till the end of file
{ /* ... */ }
Do not check input.eof().

this code compiles on my computer and runs but not on server [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 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?.