Read File and store in a array of chars - c++ - c++

I'm trying to open a file and save the information there in an array of chars, however I'm not getting it. To save in a string use this:
int main(){
string line1;
ifstream myfile;
myfile.open("example.txt");
if(!myfile){
cout<<"Unable to open the file."<<endl;
exit(0);
}
while(getline(myfile,line1)){
ReadFile(myfile);
}
}
And It works.
When I use an array of chars, I code like this:
int main(){
int size=100;
char line1[size];
ifstream myfile;
myfile.open("example.txt");
if(!myfile){
cout<<"Unable to open the file."<<endl;
exit(0);
}
while(myfile.peek()!EOF){
line1[size]->ReadFile();
}
}
The function ReadFile is this:
void ReadFile(ifstream &is){
char aux[100];
is.getline(aux,100);
}

To read in an array of characters, or text, you can use std::getline and std::string:
std::string text;
std::getline(myfile, text);
To process text lines in a file:
std::string text;
while (std::getline(myfile, text))
{
Process_Text(text);
}
Don't use arrays of characters, as they can overflow. Also, instead of using == to compare, you'll have to use strcmp. Always verify that your array of characters is terminated by a nul character, '\0', otherwise the string functions will go beyond your array, not stopping until a nul is found.
Edit 1: Space separated
To read in text that is space separated, use:
std::string text;
myfile >> text;
Edit 2: Counting characters in a string
You can count characters in a string by using another array.
unsigned int frequency[128] = {0}; // Let's assume ASCII, one slot for each character.
// ... read in string
const size_t length(text.length());
for (size_t index = 0; index < length; ++index)
{
const char letter = text[index];
++frequency[letter];
}

Related

How to read in individual characters from txt.file in C++?

I have a txt file that contains individual characters line by line. I am kind of confused as to how to read that line by line when the getline function takes in string?
Also would it be possible to store char in a vector? Or would it still work if I stored those individual characters as strings?
code show as below:
vector<char> res;
int count = 0;
ifstream fin;
fin.open("***.txt");
string str;
while (!fin.eof())
{
getline(fin, str);
res[count++] = str;
}
fin.close();

How to convert all file characters to uppercase or lowercase?

I tried to take every character in a file and use with toupper() and tolower() functions. But I can't put the result instead of the character.
I used a vector to solve it.
Is there an easy way to solve this?
void UpperCase(){
fstream file;
char name[81] , ch;
vector<char> container;
cout << "Enter the file name : ";
cin >> name;
file.open(name,ios::in);
while(!file.eof() && !file.fail()){
file.get(ch);
container.push_back(toupper(ch));
}
file.close();
file.open(name,ios::out);
for(int i=0 ; i<container.size()-1 ; ++i){
file.put(container[i]);
}
file.close();
return;
}
Here is an efficient method:
char buffer[4096];
std::string name;
std::cout << "Enter filename: ";
std::cin >> name;
std::ifstream input(name.c_str(), ios::binary);
const std::string out_filename = name + ".upper_case";
std::ofstream output(out_filename.c_str(), ios::binary);
while (input.read(buffer, sizeof(buffer))
{
const unsigned int chars_read = input.gcount();
std::transform(&buffer[0], &buffer[chars_read],
&buffer[0], toupper);
output.write(buffer, chars_read);
}
The above code reads in a block of characters, then transforms them to uppercase, then writes the block to another file.
Writing to another file is a safe practice, and you don't need to read the entire file into memory.
You can change the size of the buffer to make the program more efficient. Recommend sizes are multiples of 512, since that is a standardized size for a hard drive sector.
Edit 1:
If you are allergic to std::transform, replace the call with a loop to convert the characters.

How to read a .txt file using c-strings?

I'm working on a project for school and I need to read in text from a file.
Sounds easy peasy, except my professor put a restriction on the project: NO STRINGS
("No string data types or the string library are allowed.")
I've been getting around this problem by using char arrays; however, I'm not sure how to use char arrays to read in from a file.
This is an example from another website on how to read in a file with strings.
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The important line here is while ( getline (myfile,line) );
getline accepts an ifstream and a string (not char array).
Any help is appreciated!
Use cin.getline. Refer to this site for the format: cin.getline.
You can write something like this:
ifstream x("example.txt");
char arr[105];
while (x.getline(arr,100,'\n')){
cout << arr << '\n';
}
ifstream has a method named get() that reads the contents of the file into a char array. get() takes, as parameters, a pointer to the array, and the size of the array; then fills the array up to the given size, if possible.
After get() returns, use the gcount() method to determine how many characters have been read.
You can use then, and a simple logical loop, to repeatedly read the contents of the file, in size-chunks, into an array, and collect all the chunks read into a single array, or a std::vector.
You can use the int i = 0; while (scanf("%c", &str[i ++]) != EOF) to judge the end of text input. str is the char array include newline which you wanted, and i is the input size.
You can also use while(cin.getline()) to read per line every loop in C++ style:
istream& getline (char* s, streamsize n, char delim ); just like below:
const int SIZE = 100;
const int MSIZE = 100;
int main() {
freopen("in.txt", "r", stdin);
char str[SIZE][MSIZE];
int i = -1;
while (cin.getline(str[++ i], MSIZE)) {
printf("input string is [%s]\n", str[i]);
}
}

Creating String Array from CSV

I have a csv file of atomic elements with atomic number, symbol, and name. The file is formatted as:
1,H,Hydrogen
2,He,Helium
3,Li,Lithium
...
I'd like to create an array of the symbols referenced by the atomic number. ie. ArrayName[32]="Ge";
I've been trying to use sscanf but it hasn't been working. rough code below:
char temp[200];
float temp_z;
std::string temp_ele;
std::string temp_name;
while(!fin.eof())
{
fin.getline(temp,200);
sscanf(temp, "\"%f\",\"%s\", \"%s\"",&temp_z, &temp_ele, &temp_name);
cout<<temp_z<<endl;
cout<<temp_ele<<endl;
cout<<temp_name<<endl;
}
Read every line of your file with this loop :
string line;
ifstream myfile;
myfile.open("myfile.txt");
if(!myfile.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
while(getline(myfile, line)) {
// Split line by comma to get what's your want
}
Then split every line by comma to get every element of the line.
You can read each element like so:
string theStrings[200]; //initialize to correct size
int i = 0;
string name;
while(!fin.eof())
{
getline(thefilestream, name, ',' );
theStrings[i++] = name;
cout<<name<<endl;
}

Parsing a string of numbers into an integer array

I have a text file with numbers ranging from 0-255 separated by commas. I want to be able to store each of these numbers into an integer array. An example of what the text file might contain is;
"32,51,45,12,5,2,7,2,9,233,132,175,143,33..." etc
I have managed to get my program to store the data from the text file as a string and output them on the screen. What I need to do next is store the values of that string in an integer array, separating the numbers by the commas.
Here is the code I have written so far, which I am having problems getting it working;
int _tmain(int argc, _TCHAR* argv[])
{
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
//STRING CONVERSION
std::string str = line;
std::vector<int> vect;
std::stringstream ss(str);
int i = 0;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
system("pause");
return 0;
It looks like your code for tokenizing your string is bit off. In particular you need to make sure you call atoi() on the string of your integer to get an integer. I'll focus on the parsing of the string though.
One thing you could use is C's strtok. I recommend this mainly because your case is rather simple, and this is probably the simplest way to go about it.
The code you'd look for is essentially this:
char* numStr = strtok(str.c_str(), ",");
while (numStr)
{
vect.push_back(atoi(numStr));
numStr = strtok(NULL, ",");
}
strtok() takes two arguments: a pointer to the C-style string (char*) you're tokenizing, and the string of delimiters (note that each character in the delimiter string is treated as its own delimiter).
I should mention that strtok is not thread-safe, and you also have to ensure that the string you extract from the file ends with a null character \0.
The answers to this question provide many alternatives to my solution. If you'd prefer to use std::stringstream then I suggest you look at the 5th answer on that page.
Regarding your trouble with PDBs, what is the exact error you're getting?