SaladSnake
SaladSnake

Reputation: 167

Grabbing values from a file to see if they are int or string

I've trying to grab a value from a file and see if it's an int or a string. if its a int it should go into the tempNum var if it's a string it should go into the tempString var. The rest of my code is written i just need to get that value into the correct variable.

while (!myFile.eof())
{

    try
    {
        myFile >> tempNum;
    }
    catch (invalid_argument&)
    {
        myfile >> tempString;
    }


}

Second attempt:

ifstream myFile;
myFile.open("data.txt");

    while (myFile >> tempString)
    {
        tempNum = -1;
        tempString = "-0";
        bool isInteger = true;
        for (int i = 0; i < tempString.length(); ++i)
        {
            if (!isdigit(tempString[i]))
            {
                isInteger = false;
                break;
            }
        }
        if (isInteger)
        {
            tempNum = stoi(tempString);
            if (tempNum != -1)
            cout << tempNum;
        }
        if (tempString != "-0")
        cout << tempString;

    }
system("pause");
return 0;

Upvotes: 0

Views: 47

Answers (2)

Donald
Donald

Reputation: 641

When you read from a file, you should be reading it into a string:

while (fileVar >> myString)
{
   // Do something with the string from file
}

So, you can test for each individual character to see what the whole is. Below is how to separate only the int's. Otherwise, if you want separate strings that contain only letters, then replace the "isdigit()" function with "isalpha()", or test for specific characters.

// Input validation (int)
bool isInteger = true;
for (int i = 0; i < myString.length(); ++i)
{
    if (!isdigit(myString[i]))
    {
        isInteger = false;
        break;
    }
}
if (isInteger)
{
   int myInt = stoi(myString);
}

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249143

if (myFile >> tempNum) {
  // it worked as an int
} else if (myfile >> tempString) {
  // it worked as a string
}

Upvotes: 2

Related Questions