c-string vs Strings

Started by
17 comments, last by Oldstench 16 years, 11 months ago
I want to store each individual word into a variable but it isnt working
int main(){using namespace std;string word[100];ifstream readFile("story.txt");//File contains blocks of text like paragraphs.if(readFile.fail()){   cout << "File failed to open!";   exit(1); }getline(readFile,str);//Will this read words into word[0],word[55], etc?cout << word[5];//Should output a word//Suppose the 1st line of text is,"I love baseball and beer nuts"Shouldn't:word[0]= "I"word[1]= "love"word[2]= "baseball"word[3]= "and"word[4]= "beer"word[5]= "nuts"

I'd say Character I/O is the hardest thing I have encountered in my class, even arrays and pointers were not as hrd to undeerstand

}
Advertisement
Quote:Original post by bluefox25
I want to store each individual word into a variable but it isnt working
*** Source Snippet Removed ***
I'd say Character I/O is the hardest thing I have encountered in my class, even arrays and pointers were not as hrd to undeerstand

}


Not quite. First of all, you haven't declared a variable "str" anywhere.

But more to the point, std::getline stores a single line in a single string.
From there, we can parse it more.

Instead of the arbitrary limit of 100 strings in a line (which in most places will be far too much, but if it is ever too little then you'll be in trouble) we will use another std::container. I see you are already using std::string so you will be familiar with how they "just work" when it comes to sizes, they grow big enough anything you try fit in them. We have the equivalent for arrays in the form of std::vector. We can simply push_back something into the vector to add something. We can ask the std::vector how many elements it has, so we can iterator over it (or we could use iterators, but Ill try keep it as simple as possible):
#include <vector>#include <string>#include <fstream>// other includes// this example will read all the lines from the file// and print them all.int main() {   std::vector<std::string> lines;   std::ifstream readFile("story.txt");   std::string currentLine;   while( std::getline(readFile,currentLine) ) {      lines.push_back(currentLine);   }   // now in between here we might do something interesting.   for( int i = 0; i < lines.size() ; ++i ) {      std::cout << lines << '\n';   }}


Now we come to parsing the individual lines. The Standard C++ Library includes a class called std::stringstream. Its like a std::fstream, or std::cout/std::cin. But it works in memory, nothing need be printed or sent to a file. Also we can read and write to it. So we can throw in an string, and read it out a int.

Example:
// attempts to read the first item in the// string as an integerint intFromString( const std::string & input ) {   std::stringstream stream;   stream << input;   int value;   stream >> value;   return value;}


This is a simple way to do string/integer conversions if you don't have boost.

It is used like so:
std::stringstream stream;// a string with a string, int and float as an example:stream << "jimmy 7 3.14";std::string name;int age;float pi;stream >> name >> age >> pi;std::cout << "Person with name: " << name << " age: " << age << " and who thinks pi is " << pi << '\n';


Now, our needs are actually simpler. We have a bunch of words in a line.
We need to separate into a bunch of identical objects. We can store them in a std::vector instance to aid us.
std::vector<std::string> parse( const std::string &line ){   std::vector<std::string> words;   std::stringstream stream;   stream << line;   std::string currentWord;   while( stream >> currentWord ) {       words.push_back(currentWord);   }   return words;}


I hope you'll be able to build on this to do whatever you are trying.
Thanks alot. That is interesting. I guess Im still learning about what techniques to best use. I try and break the problem down into small parts but sometimes I get stuck on what process to use to try and solve a subtask, sometimes I try and it works and other times it does not and I get frustrated. I will stick with it though, practice is the only wy to lear!! Trial and error.
For example, I am trying to write a simple loop to prompt a user to continue, what is the most efficient way to implement this? Within a function or in main?
I wrote this:
void promptToContinue(){    using namespace std;      char ans = 'Y'     cout << "Would you like to continue ?" << endl          << "Press 'Y' for yes,'N' for no << endl;     cin >> ans;     if(ans =='Y'){       continue;     }else{        exit(1);     }}

I got this code marked down b/c it needed the ans to be pass by reference param. How could I use ans referenced if I hadnot prompted user for an answer?
He probably wanted this: but how would this work?
 void promptToContinue(ifstream& fin, char& choice){}
Shouldn't this piece of code give me an error? It doesn't in DevC++
char cString1[] = "Man Utd won the Premiership in 2007!!!";char cString2[] = "";strcpy(cString2, cString1);cout<< "cString1 = " << cString1 << endl;cout<< "cString2 = " << cString2 << endl;

It outputs something like:
cstring1 = Man Utd won the Premiership in 2007!!!
cstring2 = Man Utd won the Premiership in 2007!!!
Quote:Original post by bluefox25
Shouldn't this piece of code give me an error? It doesn't in DevC++
*** Source Snippet Removed ***
It outputs something like:
cstring1 = Man Utd won the Premiership in 2007!!!
cstring2 = Man Utd won the Premiership in 2007!!!


Well, you're writing to areas of memory outside of the memory allocated for cString2, that is a very dangerous thing to do as you never know what might be stored there. I guess it was pure luck you didn't overflow or crash.
Best regards, Omid
I've been having some issues with DevC++ not catching errors that are caught in VSC++. I like using DevC++ b/c it is a small sized compiler and works well.
I thought it would cause a crash or error for the same reason. I am going to try on it VSC++ but I am almost sure it will blow up!!

Is there any way to correct this problem? Besides switching compilers
Quote:Original post by bluefox25
I've been having some issues with DevC++ not catching errors that are caught in VSC++. I like using DevC++ b/c it is a small sized compiler and works well.
I thought it would cause a crash or error for the same reason. I am going to try on it VSC++ but I am almost sure it will blow up!!

Is there any way to correct this problem? Besides switching compilers


The only reliable way to deal with the class of problem you just showed is not to create it in your code. Not only do neither of the compilers you mentioned *actually* catch it (if they could, you'd get an error when you tried to compile, not a crash when it runs), but playing around with the compiler options might cause it to "work" where it wasn't working before, or "stop working" where it was. And in fact, in the general case, it is impossible for the compiler writer to do anything about it. That's just how C++ is designed: you specify where to write things -ultimately - in terms of machine addresses, and the addresses you indicate don't necessarily correspond to the addresses you want, or even to memory that belongs to you.
Thanks for all of your help guys. I would've been even more lost w/o our tips and explanations!! Just wrapped up my intro course and I will be receivingmy grade soon!!
On to Data Structures in the Fall.

So what now? I feel as if things are realy clicking in from all the stuff I learned from the start of the course up until now and I am eager to learn and practice more but I have no ideas on what to work on? I guess a game? Should I even attempt that yet or continue my pursuit of knowledge?

I had problems withh character I/O and reading lines of text and what not

How do I output different style fonts and colors in C++? Can you make text bold or in italics?

If I have a menu prompt the user, aftr their selection, how do I make the screen clear the menu and flash the new menu or text?
Quote:Original post by bluefox25
How do I output different style fonts and colors in C++? Can you make text bold or in italics?

If I have a menu prompt the user, aftr their selection, how do I make the screen clear the menu and flash the new menu or text?


You should check out this link.

This topic is closed to new replies.

Advertisement