What is the problem with the following c++ code? [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 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.

Related

Why is this Code giving an "stray '\' in program" error? [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 1 year ago.
Improve this question
I came across this question while practicing Pointer questions and according to my understanding I thought option C would be correct but Option D was the correct answer, so I ran the code on VS Code and it did give a Compilation error.
Strings are terminated by NULL character then why an error is occurring if the for loop is checking for the occurrence of the NULL character.
Please can somebody explain what is the problem with this code? Here is the actual code:
#include<iostream>
using namespace std;
int main() {
char st[] = "ABCD";
for(int i = 0; st[i] != ‘\0’; i++) {
cout << st[i] << *(st)+i << *(i+st) << i[st];
}
return 0;
}
‘ (U+2018 LEFT SINGLE QUOTATION MARK) and ’ (U+2019 RIGHT SINGLE QUOTATION MARK) are Unicode characters, and your source file is saved in UTF-8.
You likely copied this code from some website which used these characters.
You need to use ASCII ' (U+0027 APOSTROPHE) instead:
st[i] != '\0'

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.

My codes work well In Dev c++ IDE, but in linux terminal, it doesn't. (especially in the part of 'while' loop.) [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 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.

stopword removal in C++ code [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
can Anyone help me make the stopword to be removed..I could not.. still appear after run!
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
char filename[50]; //open file
ifstream example;
cin.getline(filename , 50);
example.open(filename);
if(!example.is_open())
{
exit(EXIT_FAILURE);
}
char word[50];
example>>word;
while (example.good()&&word!="a"&& word!="an"&&word!="be"&& word!="at"&& word!="the")
{
cout <<word<<" "; // remove stopwords
example>>word;
}
system("PAUSE");
return 0;
}
can Anyone help me make the stopword to be removed..I could not.. still appear after run!
You cannot compare C-strings with the == operator. The easiest solution to your problem will be to use std::string:
string word;
example >> word;
while (example.good() && word != "a" && word != "an" && word != "be" && word != "at" && word != "the")
{
cout << word << " "; // remove stopwords
example >> word;
}
On the other hand, this will actually not remove all, as you call it, stopwords. It will just print all words until the first “stopword” is read, and then the whole loop will stop.
The problem is that you're using C-style strings, which are fiddly to use correctly. The simplest option is to use the C++ strings library:
#include <string>
std::string word;
and the rest of your program should work as expected. This will also prevent the hideous stack-corruption bug that your program will experience if an input word is too long.
If you really want to muck around with character arrays for educational purposes, then you'll need to use the C strings library to compare them:
#include <cstring>
if (std::strcmp(word, "a") != 0 && ...)
Your code compares the address of the array containing the input word with the address of a string literal; these will never be equal.
When removing stopwords, remove not only a few of them.
In addition, you should apply the Porter algorithm to your piece of code.
The Porter Stemmer has to be applied regarding string similarity if you wanna check a filtered text.
Yes, it is in C, but only applying a few words (like your question) is not an adequate removal procedure of stopwords. The C code gives you an impression if you really wanna stem in addition to removal of stopwords. This depends on the purpose.
Have done both in 2008 to filter many text fragments. Both was relevant.
hth
A competent compiler with warnings turned on will fix your problem for you. Here's what mine said:
warning: result of comparison against a string literal is unspecified (use strncmp instead)
[-Wstring-compare]
while (example.good()&&word!="a"&& word!="an"&&word!="be"&& word!="at"&& word!="the")
^ ~~~

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();
}