如何创建由从文本文件中读取的字符组成的字符串
How do I create a string consisting of characters read from a text file?
我正在尝试读取代码并对其进行格式化,以便它在某个点之后切断并转到新行。起初,我试图简单地继续显示连续的字符,并在此时读取的字符数超过限制后使其进入换行符。但是,如果某个单词超出限制,我需要让该单词开始新行。由于我完全不知道如何仅使用字符来做到这一点,因此我决定尝试使用字符串数组。我的代码如下
char ch;
string words[999];
//I use 999 because I can not be sure how large the text file will be, but I doubt it would be over 999 words
string wordscount[999];
//again, 999. wordscount will store how many characters are in the word
int wordnum = 0;
int currentnum = 0;
//this will be used later
while (documentIn.get(ch))
{
if (ch != ' ')
//this makes sure that the character being read isn't a space, as spaces are how we differentiate words from each other
{
cout << ch;
//this displays the character being read
在我的代码中,我想将所有字符"保存"为字符串,直到字符成为空格。我不知道该怎么做。谁能在这里帮我?我想会是这样的;
words[wordnum] = 'however i add up the characters'
//assuming I would use a type of loop to keep adding characters until I reach a
//space, I would also be using the ++currentnum command to keep track of how
//many characters are in the word
wordscount[wordnum] = currentnum;
++wordnum;
使用输入文件流循环添加它们的单词到向量,然后 vector.size() 将是字数。
std::ifstream ifs("myfile.txt");
std::vector<std::string> words;
std::string word;
while (ifs >> word)
words.push_back(word);
默认情况下将跳过空格,while 循环将继续,直到到达文件末尾。
我不知道
你真正想做什么。
如果要从文件中恢复每一行,可以这样做:
std::ifstream ifs("in");
std::vector<std::string> words;
std::string word;
while (std::getline(ifs, word))
{
words.push_back(word);
}
ifs.close();
函数 std::getline() 不会省略空格,例如 ''、'\t' ,而这将通过 ifs>> word 进行解散。
相关文章:
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 从矢量C++读取字符时出现问题
- 从格式化输入操作中获取读取字符数
- 使用 cin.get 读取字符数组
- 按下回车键时,如何使数组停止读取字符
- C++:读取字符是不正确的
- 如何从输入文件中读取字符并将其存储到向量中?
- 线程函数无法从堆上分配的缓冲区中读取字符
- 使用 cin.get() 读取字符
- C++:使用 fgets() 读取字符输入时出错
- C++ 从文件中读取字符,计算每个字符并进行排序
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 逐字读取字符数组,无需字符串函数
- 是否有任何方法可以在用户输入文本时读取字符
- 从字符串中读取字符时出错
- 如何按字符从文件到2D数组读取字符
- 重载>>运算符和读取字符
- 从堆栈中读取字符后,如何修复不正确的文件输出
- 如何从文件中读取“”字符
- 读取字符 * 始终具有相同的地址