Anthony Prabhakr Anthony Prabhakr - 1 month ago 13
C++ Question

When i run same c++ programm by terminal and same programm in ide (CLion) output is different why?

using namespace std;

void print(vector<string>str)
{

vector<string>::iterator it=str.begin();

while (it!=str.end())

{

cout<<*it<<endl;

it=it+1;
}
}

void collectWord(vector<string>&str,string line)
{

const char* delim=" ,.-";

char* l =new char[line.length()+1];

strcpy(l,line.c_str());

char *pch;

pch=strtok(l,delim);


while (pch!=NULL)

{

// cout<<pch<<endl;

str.push_back(pch);

pch=strtok(NULL,delim);

}

delete[] l;

}

int main() {

string line;
vector<string>spam;

ifstream spamfile("spam.txt");
if (spamfile.is_open())
{
while (getline(spamfile,line))
{

collectWord(spam,line);
}
spamfile.close();
}
else{
cout<<"Unable to open file"<<endl;
}




print(spam);

return 0;

}


When i run this programm in terminal output is ok but when i run it into ide(Clion(c/c++)) output is different

Answer

ifstream spamfile("spam.txt");

This opens the file spam.txt relative to the "Current Working Directory" (CWD). CLion runs your executable from a different folder than when you run it from command line, so the CWD is different.

You need to make sure that spam.txt exists in the directory where CLion is building your executable.

edit: alternatively I think CLion will allow you to choose which CWD to run the executable from, or you could give a fully-specified path for the file (like C:\MyStuff\spam.txt)