how do I take characters from a file and put them into a string so I can compare them??
your help is greatly appreciated
how do I take characters from a file and put them into a string so I can compare them??
your help is greatly appreciated
You can use the get method to put them into a single character.
http://www.cplusplus.com/ref/iostream/istream/get.html
And then you can use the += operator for string to concat it to the end of a string.
However, if you want to compare single characters, you don't need to use strings.
Code:#include <iostream> #include <string> using namespace std; int main() { std::ifstream input("inputfile.txt"); std::string s; char current; while (!input.eof()) { current = input.get(); s += current; } return 0; }
thank you!
that's exactly what I was looking for
I can't get the += to work
my compiler only wants =+, and that doesn't work with chars.
plus it won't let me declare a variable with string.
please help
OK, depending in what compiler you have you may need:
One of these options should work.Code:#include<string.h> //or #include<cstring> //or #include<cstream>
=+ is different than +=, because += adds to an integer, where =+ is meaning "equal plus"
ok, I can include string.h, but not the others, but I still can't use +=, do you guys want to see my code?
=+ really means taht the number after that is positive . post the code.
What compiler are you using?
Visual C++ 6.0
You should be able to use +=, so yes please post your code.
Code://readtext.cpp #include <iostream.h> #include <fstream.h> #include <string.h> main() { char x; char current[6]; ifstream infile; infile.open("text.txt",ios::in); while(infile) { infile.get(x); current += x; } return 0; }
i guess i didnt exactly understand. i dont think that would work because would this:
use strlen():Code:int Int = 5; int Array[5]; Array += Int;
Str[ strlen( Str ) ] = Chr;
I'm new to programming, can you give me an example on how to use strlen in my situation?
Thanks
string current;
while(infile);
{
infile.get(x);
current += x;
works because the += operator is overloaded for the STL string class of which current is an instance.
However, the += operator is not available for Cstyle, null-terminated char array type strings. You need to use strcat() for that.
//declare an string big enough to hold what you want
char * current = new char[10000000];
current[0] = '\0';
//declare a second string to act as input
char * input[2];
input[1] = '\0';
//read the file one char at a time, placing the char as the first
//element in the string called input
while(infile)
{
infile.get(input[0]);
//then concatenate the string called input onto the string called
//current
strcat(current, input);
//etc.