-2
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    fstream infile;
    infile.open("letter.txt");

    string s;
    char charArray[11];

    char x;
    while (!infile.eof())
    {
        infile.get(x);
        x = tolower(x);


        for (int i = 0; x != ' '; i++)
        {
            charArray[i] = x;
        }
        string mystring(charArray);
        cout << mystring;

    }


    system("pause");
}

In my C++ program I am to read from a file one character at a time and stop when the loop reaches a space (this would indicate the end of a single word). Then, I want to assign the contents of the char array to a string variable.

I know I can read one word at a time from the file, however for my assignment this is not a suitable solution.

My difficulty is converting from char array to a string variable .

scohe001
  • 15,110
  • 2
  • 31
  • 51
Artin
  • 1
  • 1
  • 2

1 Answers1

1

std::string actually has a constructor that takes a C-style string! As long as you make sure your char array is null terminated, you can do:

char myArr[]; //Make sure it's null terminated!
std::string myString(myArr);
scohe001
  • 15,110
  • 2
  • 31
  • 51
  • I added my code. However, I get a an exception error after the code compiles. – Artin Nov 07 '18 at 23:26
  • @Artin I said it twice and gave you a link, but I’ll say it again: **your char array *must be NULL-terminated.*** – scohe001 Nov 07 '18 at 23:46