2016-02-15 28 views
-2

我試圖從給定的txt文件在linux終端中創建用戶。每行的格式在文本文件中是「Josh:0001」。 Josh是用戶名,0001是密碼。我可以爲每一行創建一個字符串,但我無法弄清楚如何將字符串拆分爲「:」字符。從文本文件中添加linus用戶的C++程序

#include <iostream> 
#include <cstdlib> 
#include <string> 
#include <sstream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
cout << "Hello World" << endl; 
//system("mkdir user1"); 


string anyCommand="", name, userpassword; 


//code to open a file 
string users[120]; 
string line; 
//int userCount=0; 
ifstream myfile ("users.txt"); 
if (myfile.is_open()) 
{ 

for(int i = 0; i < 1; i++) 
{ 
    //code to read a user from the input file 
    getline(myfile,line); 
    stringstream temp(line); 




    name += temp.str(); 


    //useradd vs. userdel 
    anyCommand = "useradd " + name ; 

    cout << anyCommand << endl; 
    system(anyCommand.c_str()); 

    //anyCommand = ""; 
    //userpassword = "sosu-2014"; 
    //set the command, e.g., system("echo john:sosu-2014 | chpasswd"); 
    anyCommand = "echo " + name + ":" + userpassword + " | chpasswd"; 
    cout << anyCommand << endl; 
    system(anyCommand.c_str()); 

}} 

//code to close a file 
cout << "Job Done!" << endl; 

return 0; 
} 

對不起,我註釋掉了一些東西,嘗試不同的方法。

+1

[使用getline和while循環來分割字符串]可能的重複(http://stackoverflow.com/questions/5757721/use-getline-and-while-loop-to-split-a-string) – LogicStuff

+0

Don不要爲這個爛攤子道歉;解決這個爛攤子。 –

回答

0

要分割字符串,請使用std :: string中的find_first_of(或find_last_of)和substr函數。

+0

我還是不明白這一點..我知道非常基本的代碼,我的字符串沒有任何空格。 – turboz8607

相關問題