Plz help!!

Sep 29, 2015 at 6:57am
Why is this simple code not working ?

1
2
3
4
5
  String itemname;
  getline(cin,itemname);
  string newname= "item\\"+ itemname;
  ifstream getstock;
  getstock.open(newname);// problem 
Last edited on Sep 29, 2015 at 6:59am
Sep 29, 2015 at 7:12am
What type of error are you getting? Because from what I can tell, on line 1, you have string type accidentally capitalized to "String". Unless this is a custom class that you made for the purposes of your program, there's nothing syntactically wrong with your code.
Sep 29, 2015 at 7:49am
After solving that "string" problem i think i am unable to open the newname file in line 5. I know this because my earlier code was :

<code>
void getstock ( string itemname)
{
string newname = "item\\" + itemname;
ifstream getstock;
getstock.open(newname);

if (getstock.fail())
{
cerr << "sorry unable to display stock";
getstock.close();
}
else
{
getstock>> itemstock;
cout << "the stock for "<< itemname <<"is"<< itemstock;
getstock.close();
}
}
</code>
this function is part of a class in which itemstock is already defined.i am always getting the error of "sorry unable to dislplay stock".
Last edited on Sep 29, 2015 at 7:53am
Sep 29, 2015 at 8:24am
Might just be a hunch but it may have something to do with the slashes in your "item\\". I don't think the compiler (whichever one you use) should read them as null or empty characters, but I'm no expert on compilers.

Also there maybe be an issue with order of operation, so I would do ("item" + itemname) if it allows that.
Sep 29, 2015 at 9:27am
it may have something to do with the slashes in your "item\\".
Double slash is escape character (slash) + escaped character (slash) together they will embed a single \ into string (as slash is a special symbol in strings, you canot use it directly)

Do you really have a file with that name? Can it be open already by another stream?
Sep 29, 2015 at 11:34am
Yes , there is a folder named item in which the file is present that is why i used \\.

Sep 29, 2015 at 11:40am
DO you have that file opened elsewhere? You cannot (usually) open an already opened file.
Topic archived. No new replies allowed.