为什么无法将字符串的元素按索引号附加到 C++ 中的新字符串?

Why isn't it possible to append an element of a string by its index number to a new string in C++?

本文关键字:字符串 C++ 索引 元素 为什么      更新时间:2023-10-16

我以前曾在Python中编程。我一直在尝试在C 中复制类似的方法。

我打算做的事情:通过" CIN"从用户那里获取" n"的情况,并且对于每种情况,请使用字符串输入" str"。迭代字符串" str"的每个索引,将偶数索引位置的元素打印在一起,然后是一个空间,然后是奇数索引位置的元素。

我想实现的示例是:用户输入:航空输出: arnuis eoatc

下面显示的程序是我的C 代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int N;
    cin>>N;
    for(int i=0; i < N; i++){
        string str;
        cin>>str;
        string even;
        string odd;
        for(int j=0; j < str.size(); j++){
            if (j % 2 == 0){
                even.append(str.at[j]);
            }
            else if (j % 2 != 0){
                odd.append(str.at[j]);
            }
        cout<<even<<" "<<odd<<endl;
        }
    }
    return 0;
}

当我尝试运行上述代码时,下面显示的错误消息直接从我的编译器获得:

solution.cc: In function ‘int main()’:
solution.cc:20:37: error: invalid types ‘<unresolved overloaded function     type>[int]’ for array subscript
                 even.append(str.at[j]);
                                     ^
solution.cc:23:36: error: invalid types ‘<unresolved overloaded function     type>[int]’ for array subscript
                 odd.append(str.at[j]);
                                    ^

根据我的理解,编译器说我不能以这种方式将字符串的索引元素附加到另一个字符串。我试图搜索其他论坛上C 无法做到这一点的原因,但无法得到答案。你能启发我为什么吗?

您有几个错误。

  1. str.at[j]需要是str.at(j)str[j]
  2. 您使用的string::append()版本需要另一个参数。

    basic_string& append( size_type count, CharT ch );
    

    您需要使用:

    even.append(1, str[j]);
    

    odd.append(1, str[j]);
    

,因为没有.append超负荷需要一个char(您也有语法错误(。您可以通过多种方式做到这一点。

even += str[j]; ... odd += str[j];

或范围检查

even += str.at(j); ... odd += str.at(j);

或者您仍然想使用.append

even.append(1, str[j]); ... odd.append(1, str[j]);