• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 205
  • Last Modified:

Reading Strings into variables from a text file in C++

I would like to be able to read in strings into two variables and also an into into a third I'd like to do this from a text file.  This is what I have so far.

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
      string name = " ";
      string stadium = "";
      int wins = 0;
      ifstream inFile;
      inFile.open("c:\file.txt",ios::in);

      //BinarySearchTree<BaseballTeam> BaseballTree;
                inFile>> name;
      inFile>> stadium;
      inFile>> wins;
                cout<<wins<<endl;
      cout<<name<<endl;
      cout<< name<<endl;

      return 0;
}

I use the cout statements to see if anything was actually read into the variables.
Here is the sample text file .

St.LouisCardinals
BuschStadium
14
ChicagoCubs
WrigleyField
9
When i run this, the variables keep there default values and nothing is read into them.   Any suggestions?
0
hess586
Asked:
hess586
  • 3
1 Solution
 
AxterCommented:
Hi hess586,
> >inFile.open("c:\file.txt",ios::in);
You need to use two \\ for every one \
inFile.open("c:\\file.txt",ios::in);

David Maisonave :-)
Cheers!
0
 
jkrCommented:
>>Any suggestions?

1st of all, change

     inFile.open("c:\file.txt",ios::in);

to

     inFile.open("c:\\file.txt",ios::in);

inFile is not being opened correctly, thus the reads will fail.
0
 
AxterCommented:
The \ character is a special character, and if you want to represent a back slash character in a C/C++ string, you need to use two of them for each one.

char FileName[] = "c:\\windows\\system\\foofoo.exe";
0
 
AxterCommented:
hess586,

Isn't that the same answer I posted????
Which I posted first........
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now