【问题标题】:Reading String of Varied Sizes // String Manipulation C++读取不同大小的字符串 // 字符串操作 C++
【发布时间】:2018-02-16 12:22:57
【问题描述】:

所以我刚开始学习 C++,我的教授简要介绍了地址 (&) 和取消引用 (*) 运算符。我不精通 C++,但我一直在寻找零件并使用常识来组合到这段代码中。构建失败,请帮忙!

Assignment - 编写一个程序,不断读取不同大小的字符串。如果输入字符串的长度大于 1,则将其存储在向量中。当输入字符串的长度为 1(单个字符)时,您将输出存储在向量中的字符串,该字符串的第一个字母与输入字符匹配。在阅读字符串“quit”时继续这样做。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;


int main()
{
    string input;
    char* output;
    vector<string> name;

    while (input != "quit") {
        cin >> input;

        if (input.length == 1) {
            for (int i = 0; i < name.size; i++) {

                output = &name[i].at(0);

                if (input == output) {
                    cout << name[i];
                }
            }
        }
        else {

            name.push_back(input);
        }
    }

    //system("pause");
    return 0;
}

【问题讨论】:

  • "虽然没有错误,但是编译失败" 类似于"我的车是蓝色的,但不是蓝色的"
  • 编译器错误通常包含问题的确切位置,以及编译器无法理解您的代码的原因的描述。如果您看到错误消息,则更容易识别问题;请复制到这里。
  • name.size 是一个错误。 input.length 是一个错误。
  • 我对 C++ 有点生疏,但 input.length 应该改为 input.length() 吗?如果没有,请发布您从编译中获得的错误代码。
  • 使用 char* 的原因是指向将保存在向量中的字符串的第一个字母 // 这是我的想法...我是 C++ 新手

标签: c++ string pointers address-operator


【解决方案1】:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string input;
    vector<string> name;

    cin >> input;

    while (input != "quit") {

        if (input.length() == 1) {

            for (int i = 0; i < name.size(); i++) {

                if (input[0] == name[i][0]) {
                    cout << name[i] <<endl; 
                }
            }
        }
        else {
            name.push_back(input);
        }
        cin >> input;
    }
    system("pause");
    return 0;
}

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多