user683422 user683422 -3 years ago 55
C++ Question

When trying to read from a text file in c++ it gives me a large random number

I'm trying to make a program that gets your name and greets you with it. Here is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

int main()

ifstream infile;"Info.txt");

int x;

infile >> x;

cout << "Hello " << x << endl;

return 0;

My Info.txt only contains 1 line that just says "Bob", but when I run the program all I get is "Hello 1978627034"

Answer Source

You need to read in the name as a string, not an int:

ifstream infile;"Info.txt");

string x;

infile >> x;

cout << "Hello" << x << endl;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download