【问题标题】:Trying to cout a string filled in like an array of chars but it's only cout'ing the first char in the string试图计算一个像字符数组一样填充的字符串,但它只是计算字符串中的第一个字符
【发布时间】:2015-10-13 23:57:31
【问题描述】:

在我的项目中,我正在读取一个程序集文件(现在很小,仅用于测试)。我想看看我正在阅读的内容是否是标签(我相信我的代码很好)。如果它是一个标签,我会逐个字符地获取标签的全名,然后按索引将其分配给字符串索引,以便我可以获取标签的全名以供以后使用。出于某种原因,当我计算我的标签时,它只是给了我第一个字符而不是整个字符串。我相信问题出在“cout

#include <iostream>
#include <fstream>
#include <string>
#include <map>

using namespace std;

int main(int argc, char* argv[]) {
    int counter = 0;
    char x = ' ';
    string myFileString = " ";
    string label = " ";

    if (argc < 2) {
        cout << "Error: Not enough arguments in the command line!" << endl;
    }
    else {
        ifstream myFile(argv[1]);

        if (!(myFile.is_open())) {
            cout << "Error: Could not open the file!" << endl;
        }
        else {
            while (!(myFile.eof())) {
                getline(myFile, myFileString);

                // Does not have a label
                if (myFileString[0] == ' ') {
                    cout << "No label here!" << endl;
                }
                // Has a label
                else {
                    while (myFileString[counter] != ' ') {
                        label[counter] = myFileString[counter];
                        counter++;
                    }
                    cout << label << endl;
                    counter = 0;
                }
            }
        }
    }
    cin.get();
    cout << endl;
}

【问题讨论】:

    标签: c++ string visual-studio


    【解决方案1】:

    您正在使用" " 初始化您的label,这会产生长度为1 的字符串,因此分配label[counter] = myFileString[counter] 仅在counter0 的情况下有效。尝试将一个字符附加到您的label,但首先您需要使用"" 对其进行初始化。尝试类似:

    ...
    string label = "";
    ...
    label += myFileString[counter];
    

    【讨论】:

    • 感谢马克西姆的回复!当我尝试将分配更改为 string label = "";由于某种原因,如果引号之间没有空格,我的 Visual Studio 会很合适。相反,我改变了我的逻辑以使用字符串流!这让我的整个程序变得更容易了,我想我一开始只是想努力做到这一点:/再次感谢!
    【解决方案2】:

    我改变了我的逻辑,改为使用字符串流。这提供了一种更好、更有效的方法来解决我的问题!

    if (argc < 2) {
            cout << "Error: Not enough arguments in the command line!" << endl;
        }
        else {
            ifstream myFile(argv[1]);
    
            if (!(myFile.is_open())) {
                cout << "Error: Could not open the file!" << endl;
            }
            else {
                while (!(myFile.eof())) {
                    getline(myFile, line);
                    stringstream myStream(line);
    
                    while (myStream >> word) {
                        ...
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多