0

I need to read the first letter of each word in a String array in C++. I am trying to translate a message into Pig Latin and I need to be able to determine what the first (and second) letters are. I managed to fill a string array with text from a (txt) file, but I'm really stuck on what to do next. Please help. Thank you!

string *message = NULL;//}
string tempChar, value;//This is dynamically allocating space in the string array
int size = 0;          //}

while (Input>>tempChar) {//Getting the size of the array
    size++;
}

message = new string[size];
Input.close();//This part is to make sure the file is not read two times
Input.open("example.txt");
cout << "The original message is :\n";

for (int i = 0; i < size; i++) {//This part fills and outputs the original message
    Input >> message[i];
    cout << message[i] << " ";
}

cout << "\n" << endl;
Input.close();
Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21
  • Unrelated: consider using a `std::vector message` instead of `string *message` if permitted. – user4581301 Oct 15 '19 at 02:52
  • Unrelated: `vector`, used properly, makes this advice obsolete, but rather than closing and reopening the input file you can [`seekg`](https://en.cppreference.com/w/cpp/io/basic_istream/seekg) to the beginning of the file. – user4581301 Oct 15 '19 at 02:55
  • And if not, implement your own minimal version of `std::vector`. – Jarod42 Oct 15 '19 at 02:55
  • 1
    Probably a duplicate from [this](https://stackoverflow.com/questions/34097048/selecting-only-the-first-few-characters-in-a-string-c) Use the `std::vector` and then use `substr()` function – ignacio Oct 15 '19 at 02:56
  • Or simply `message[i][0]` (1st char) and `message[i][1]` for (2nd char). Or better `message[i].at(0)` (or `.at(1)`) so bounds checking is performed. – David C. Rankin Oct 15 '19 at 04:11

1 Answers1

0
#include <string>
#include <iostream>
#include <iterator>

int main()
{
    std::string string_array[4] = {"Blue", "Red", "Orange", "Yellow"}; 
    for (int i = 0; i < std::size(string_array); ++i)
        std::cout << string_array[i].substr(0,2) << std::endl;
    return 0;
}

Requires C++17 to use std::size(), but one could use sizeof(string_array)/sizeof(string_array[0]) taking some precautions as explained here. Or, add the std::size() implementation to your code:

#include <cstdlib>

template<class T, std::size_t n>
constexpr std::size_t size(const T (&)[n])
{
    return n;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
ignacio
  • 1,181
  • 2
  • 15
  • 28
  • 1
    The only thing in this code that requires C++17 is `std::size()`. That can easily be replaced with a manual implementation in earlier versions: `template size_t size(const T (&arr)[N]) { return N; }` – Remy Lebeau Oct 15 '19 at 03:54
  • I would never have thought on doing this! Thanks @RemyLebeau. – ignacio Oct 15 '19 at 04:09