Uninitialized char* generates error

Hello. This is my code:
1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
	char* fileName;
	std::cout << "File: ";
	std::cin >> fileName;
}


And it generates this error:
error C4700: uninitialized local variable 'fileName' used


And if I try to do it this way: char* fileName = "file.txt"
I get this error:
error C2440: 'initializing': cannot convert from 'const char [9]' to 'char *'


How can I fix this?
Last edited on
Also, this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <fstream>

int main()
{
	std::string fileName;
	std::cout << "File: ";
	std::getline(std::cin, fileName);
	
	std::ifstream sqrFile(fileName.c_str());

	char info[3] = { '\0', '\0', '\0' };

	sqrFile.read(info, 3);

	std::cout << info;
}


gives the following output:
File: test.sqr
SQR╠╠╠╠╠╠╠╠╠@?∙


Because of how info is declared? Or what?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>

int main()
{
    char file_name[128] ; // declare an array to hold the file name 
    
    std::cout << "file name: " ;
    // std::setw( sizeof(file_name) ): do not accept more chars than what the array can hold
    std::cin >> std::setw( sizeof(file_name) ) >> file_name ;
    
    std::cout << file_name << "\n" ;
}


Simpler to use std::string instead of the c-style array.
Yes, using an std::string would be perfect, but it is also giving me an error if I try
to read into an uninitialized char* from a file, how can I user std::ifstream::read
to read into an std::string?
either file_stream >> my_string ; // read a whitespace delimited string
or std::getline( file_stream, my_string ) ; // read a complete line
Oh, so you can't read a set amount of bytes?
Hmmm I am currently trying to develop a
binary file format that has a width and length
for a square... Hmm
1
2
3
4
5
char bytes[128] ; // array to hold the bytes

if( file_stm.read( bytes, 32 ) ) // read 32 bytes into the array
    std::cout << file_stm.gcount() << " bytes were read\n" ; 
else std::cout << "input failed\n" ; 

Okay, thanks! :P
Topic archived. No new replies allowed.