我试图从包含句子的文件中读取并一次输出两个字母。
#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;
}
这就是我所拥有的。
output:
h he el ll lo ow eo or rl ld d
编辑&amp;运行
这就是它目前输出的内容,例如,&#34; hello world&#34;
Mirror
我该如何解决?我认为它与我的for循环调用输入[i + 1]有关,但我不知道如何组合除了这样做之外的单词。
答案 0 :(得分:2)
尝试将i ++修改为i + = 2,因为你需要跳过第二个
答案 1 :(得分:2)
这将以2个字母对打印任何内容:
#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
答案 2 :(得分:0)
以下两个字符一次打印并打印出来。它使用for
语法初始化字符,然后仅在读取两个字符成功时继续。
for(char c1{}, c2{}; infile >> c1 >> c2;) {
std::cout << c1 << c2 << ' ';
}