C++:如何一次输出两个字母的字符串?

oxalkeyp  于 2022-12-05  发布在  其他
关注(0)|答案(4)|浏览(250)

我正在尝试从一个包含句子的文件中读取,并一次输出两个字母。

IE: 
    >hello world

 Output:
        he ll ow or ld

这是我的资料。

#include<iostream>
#include<string>
#include<fstream>
#include<vector>

using namespace std;

int main()
{
    string input;

    ifstream infile;
    infile.open("wordpairs.txt");

    while(!infile.eof())
    {
        getline(infile, input);

        for(int i = 0; i < input.length(); i++) //accidentally posted wrong code last time. My apologies.
        {
            cout << input[i] << input[i+1] << " ";
        }
        cout << endl;
    }


    infile.close();
    return 0;
}

编辑和运行
这是它当前输出的内容,例如,“hello world”

output:
       h he el ll lo ow eo or rl ld d

我该如何修复它呢?我想这与我的for循环调用input[i + 1]有关,但我不知道如何合并单词,除了这样做。

zu0ti5jz

zu0ti5jz1#

这将以两个字母为一对打印任何内容:

#include <iostream>

int main()
{
    std::string input = "lo  zpxcpzx zxpc pzx cpxz c  lol";

    for (size_t i = 0, printed = 0; i < input.length(); ++i)
    {
        if (isspace(input[i]))
            continue;

        std::cout << input[i];
        printed++;

        if (printed % 2 == 0)
            std::cout << " ";
    }

    return 0;
}

印刷品:

lo zp xc pz xz xp cp zx cp xz cl ol
92dk7w1h

92dk7w1h2#

尝试将i++修改为i+=2,因为您需要跳过第二个作为第一个

erhoui1w

erhoui1w3#

下面的代码一次读取两个字符并打印它们。它使用for语法初始化字符,然后只有在成功阅读两个字符时才继续。

for(char c1{}, c2{}; infile >> c1 >> c2;) {
    std::cout << c1 << c2 << ' ';
}
nbysray5

nbysray54#

尝试使用i+=2来代替,以避免重复。如果它达到length(),则尝试使用i〈s.length()。i在这里已经将s作为字符串

相关问题