【问题标题】:Once I have the length of a string, how do I go about capturing the length number as an integer variable for use elsewhere?一旦我有了一个字符串的长度,我如何将长度数捕获为一个整数变量以便在其他地方使用?
【发布时间】:2020-04-17 02:40:39
【问题描述】:

下面是我失败的尝试,终端读取 0 作为“lengthCapture”。我试过用谷歌搜索答案,但并不高兴。

我的文本文件标题为“Boogiedy.txt”,内容为“Boogiedy, Boogiedy, Boooooo”

终端显示:

Boogiedy, Boogiedy, Boooooo
27 
0

我的代码:

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

using namespace std;

int main()
{
    string boogiedy;
    int lengthCapture = boogiedy.length();

    ifstream inputFile ("boogiedy.txt");

    if(inputFile.is_open())
    {
            while (getline(inputFile,boogiedy))
            {
                cout <<boogiedy<< '\n';
                cout <<boogiedy.length() << endl;
            }
    }
    else
        cout << "file is not open" << '\n';

    inputFile.close();

    cout << lengthCapture << endl;
}

【问题讨论】:

    标签: c++ variables capture string-length


    【解决方案1】:

    当你得到字符串的大小时,你的变量仍然是空的。

    试试这个:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string boogiedy;
        int lengthCapture = 0;
    
        ifstream inputFile ("boogiedy.txt");
    
        if(inputFile.is_open())
        {
                while (getline(inputFile,boogiedy))
                {
                    cout <<boogiedy<< '\n';
                    cout <<boogiedy.length() << endl;
                    lengthCapture += boogiedy.length();
                }
        }
        else
            cout << "file is not open" << '\n';
    
        inputFile.close();
    
        cout << lengthCapture << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      相关资源
      最近更新 更多