簡體   English   中英

我需要讀取字符串數組 C++ 中每個單詞的首字母

[英]I Need To Read the First Letter of Each Word in a String Array C++

我需要讀取 C++ 中字符串數組中每個單詞的第一個字母。 我正在嘗試將消息翻譯成 Pig Latin,我需要能夠確定第一個(和第二個)字母是什么。 我設法用(txt)文件中的文本填充了一個字符串數組,但我真的不知道下一步該做什么。 請幫忙。 謝謝!

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();
#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;
}

需要 C++17 才能使用std::size() ,但可以使用sizeof(string_array)/sizeof(string_array[0])采取一些預防措施,如此處所述 或者,將std::size()實現添加到您的代碼中:

#include <cstdlib>

template<class T, std::size_t n>
constexpr std::size_t size(const T (&)[n])
{
    return n;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM