获得字符串的长度后,如何将长度数字捕获为整数变量以供其他地方使用?

Once I have the length of a string, how do I go about capturing the length number as an integer variable for use elsewhere?

以下是我失败的尝试,终端读取 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;
}

当您获取字符串的大小时,您的变量仍然是空的。

试试这个:

#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;
}